【发布时间】:2018-04-08 23:33:31
【问题描述】:
拥有这 2 个表格(来自库存功能)
-- ins table
+------+-------------+-------------+
| id | direction | quantity |
+------+-------------+-------------+
| 1 | in | 5 |
| 2 | in | 3 |
+------+-------------+-------------+
-- outs table
+------+-------------+-------------+
| id | direction | quantity |
+------+-------------+-------------+
| 1 | out | 4 |
| 2 | out | 1 |
| 3 | out | 2 |
| 4 | out | 1 |
+------+-------------+-------------+
如何将 outs 表中的行连接到 ins 表中数量覆盖/等于加入它的 outs 行的数量的行,换句话说 如何获得这样的结果?
-- result
+------+-------------+-------------+------+-------------+-------------+
| id | direction | quantity | id | direction | quantity |
+------+-------------+-------------+------+-------------+-------------+
| 1 | out | 4 | 1 | in | 5 |
| 2 | out | 1 | 1 | in | 5 |
| 3 | out | 2 | 2 | in | 3 |
| 4 | out | 1 | 2 | in | 3 |
+------+-------------+-------------+------+-------------+-------------+
如您所见,outs 表的第 1,2 行取自/连接到ins 表的第 1 行,outs 表的第 3,4 行取自/连接到 @987654331 的第 2 行@表
注意:保证 2 个表中的数量是密封的(ins 表中的一行始终具有完全等于表 @987654333 中的 1 个或多个行的数量@)
我希望我能做这样的事情
-- sedu SQL
SELECT
whatever
FROM
outs left join
ins on outs.quantity <= (ins.quantity - previously joined outs.quantities);
【问题讨论】:
-
你运行的是什么版本? MariaDB 10.1(?) 和 MySQL 8.0 中提供了“窗口化”函数(用于累积总和)。
-
@RickJames 是
5.6.38,但我已准备好更新任何内容,以便我的应用程序可以扩展 -
@RickJames 如果你有时间,能否请你检查一下this question 关于你不规范化连续数据的规则?