【问题标题】:SQL Left Join on Multiple Tables With Different ValuesSQL Left Join 在具有不同值的多个表上
【发布时间】:2016-01-09 16:50:52
【问题描述】:

我有以下表格:

Table A :
itemCode   quantity
1           5
2           6
3           10

Table B :
itemCode   quantity
1           7
2           23
4           19

Table C:
itemCode   quantity
1           45
2           23
5           49

我想要如下所示的表格:

itemCode  A_Quantity B_Quantity C_Quantity
1            5          7          45
2            6          23         23
3            10         0          0
4            0          19         0
5            0          0          49

但是使用 LEFT JOIN 我所能做的就是拥有一个包含 itemCode 1,2 行的表,这些行是所有表共有的代码。

【问题讨论】:

  • 能否粘贴您的 SQL 查询?
  • 难道没有一个包含所有项目代码的前导表,即使它不包含数量?

标签: mysql sql left-join inner-join


【解决方案1】:

使用union all 和聚合:

select itemcode,
       max(a) as a, max(b) as b, max(c) as c
from ((select itemcode, quantity as a, 0 as b, 0 as c from a
      ) union all
      (select itemcode, 0 as a, quantity as b, 0 as c from b
      ) union all
      (select itemcode, 0 as a, 0 as b, quantity as c from c
      )
     ) abc
group by itemcode;

其他数据库中可用的替代方法是full outer join。但是,MySQL 不支持这种类型的连接。

编辑:

如果你有一个 items 表,那么使用 left join:

select i.itemcode, a.quantity as a, b.quantity as b, c.quantity as c
from items i left join
     a
     on i.itemcode = a.itemcode left join
     b
     on i.itemcode = b.itemcode left join
     c
     on i.item_code = c.itemcode;

如果你真的想要,你可以使用union 生成这样的表:

from (select itemcode from a union select itemcode from b union select itemcode from c
     i left join
     . . .

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多