拥有这两个表(来自库存功能)
-- 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
行的数量,换句话说< strong>如何获得这样的结果?
-- 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取自/ join从ins
表
注意:保证2个表中的数量被密封(ins
表中的一行总是具有完全等于表中一行或多行的数量outs
)
我希望我能做这样的事情
-- sedu SQL
SELECT
whatever
FROM
outs left join
ins on outs.quantity <= (ins.quantity - previously joined outs.quantities);
答案 0 :(得分:2)
由于某些原因,在MySQL中这很痛苦。首先,MySQL对累积总和没有很好的支持,这是你想要比较的。
第二,你的结果集有点弱。显示所有有助于每个ins
记录的outs
记录更有意义,而不仅仅是其中之一。
为此,您可以使用累积总和的连接,如下所示:
select o.*, (o.to_quantity - o.quantity) as from_quantity,
i.*
from (select o.*,
(select sum(o2.quantity)
from outs o2
where o2.id <= o.id
) as to_quantity
from outs o
) o join
(select i.*,
(select sum(i2.quantity)
from ins i2
where i2.id <= i.id
) as to_quantity
from ins i
) i
on (o.to_quantity - o.quantity) < i.to_quantity and
o.to_quantity > (i.to_quantity - i.quantity)
Here是SQL小提琴。
答案 1 :(得分:1)
子查询也可能有用
select t.id, t.direction, t.quantity, i.id, i.direction, i.quantity
from (
select id, direction, quantity,
quantity + coalesce((select quantity from outs where id < o.id order by id desc limit 1),
(select quantity from outs where id > o.id order by id limit 1)) Qty
from outs o
)t inner join ins i on i.quantity = t.Qty