如何在SQL中连接两个表,每个连接索引只获得一行

时间:2014-12-29 13:13:38

标签: mysql sql sql-server full-outer-join

如果我有以下3个表:

Table A:
Item Start_QTY
A    100
B    100

表B:

Item Purchase_QTY
A    10
C    20

表C:

Item End_QTY
A    90
B    10
C    10 

如何加入2个表以获得以下结果:

Item Start_QTY  Purchase_QTY  End_QTY
A    100  10 90
B    100  NULL 10
C    NULL 20 10

如果我执行以下操作:

Select COALESCE(a.item, b.item, c.item) as item, a.start_QTY, b.purchase_QTY, c.End_QTY from 
A as a 
full outer join 
B as b
on a.item = b.item
full outer join
C as c
on a.item = c.item

我得到以下内容:

A 100 10 90
B 100 NULL 10
C NULL 20 NULL
C NULL NULL 10

2 个答案:

答案 0 :(得分:4)

使用 FULL OUTER JOIN 从两个表中获取所有数据

试试这个:

SELECT COALESCE(A.Item, B.Item) AS Item, A.QTY, B.Price
FROM TableA A 
FULL OUTER JOIN TableB B ON A.Item = B.Item;

<强> :: EDIT ::

SELECT COALESCE(C.Item, A.Item, B.Item) AS Item, A.Start_QTY, B.Purchase_QTY, C.End_QTY
FROM TableC C  
FULL OUTER JOIN TableA A ON C.Item = A.Item
FULL OUTER JOIN TableB B ON C.Item = B.Item;

答案 1 :(得分:1)

如果您希望它在SQL Server和MySQL中都有效,那么您就无法使用full outer join。以下可能会做你想要的:

select item, max(qty) as qty, max(price) as price
from (select item, qty, null as price
      from tablea 
      union all
      select item, null, price
      from tableb
     ) ab
group by item;

仅在SQL Server中,您应该使用full outer join