在连接表时为每个id添加记录

时间:2013-11-13 10:44:32

标签: mysql join

我需要查询帮助

假设我有2张桌子

tableA
------------------------------------------
id  | name
1   | ABC
2   | DEF
3   | GHI

tableB
------------------------------------------
id  | anotherID  | Amount
1   | 1          | 1000
2   | 1          | 2000 
3   | 1          | 3000
1   | 2          | 4000
2   | 2          | 5000
1   | 3          | 6000

我需要这个清单

jointable
------------------------------------------
id  | anotherID  | Amount
1   | 1          | 1000
2   | 1          | 2000 
3   | 1          | 3000
1   | 2          | 4000
2   | 2          | 5000
3   | 2          | 0
1   | 3          | 6000
2   | 3          | 0
3   | 3          | 0

我需要每个id都有值,即使每个singleID值都是0 ..

示例: tableA有3个id& distinct another tableB有3条记录,所以我需要3 * 3 = 9条记录..

如何使用查询执行此操作?我可以使用左连接和联合,但我想知道是否有更有效的方法来实现它。

1 个答案:

答案 0 :(得分:2)

SQLFiddle demo

select T1.ID,T2.AnotherId,
       COALESCE(T3.Amount,0) as Amount
FROM TableA as T1
CROSS JOIN (Select distinct anotherID FROM TableB) as T2

LEFT JOIN TableB as T3 on (T1.id=T3.id) 
                          AND 
                          (T2.anotherID=T3.anotherID)

Order by T2.anotherId,T1.Id