我有以下表格:
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行的表,这些是所有表共有的代码。
答案 0 :(得分: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不支持这种类型的连接。
编辑:
您有一个项目表,然后使用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
. . .