在动态更改列上加入2个表

时间:2018-04-08 23:33:32

标签: mysql sql

拥有这两个表(来自库存功能)

SQL Fiddle

-- 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行

注意:保证2个表中的数量被密封(ins表中的一行总是具有完全等于表中一行或多行的数量outs

我希望我能做这样的事情

-- sedu SQL
SELECT 
    whatever 
FROM 
    outs left join 
    ins on outs.quantity <= (ins.quantity - previously joined outs.quantities);

2 个答案:

答案 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