合并两个表并在mysql中填入缺失值

时间:2011-11-18 18:25:58

标签: mysql

我在MySQL中有以下两个表:

表1:

ID Val1
1  100
2  200
3  300

表2:

ID Val2
2  50

如何将它们组合成这样的表?

ID Val1 Val2
1  100  0
2  200  50
3  300  0

3 个答案:

答案 0 :(得分:4)

SELECT Table1.ID, Table1.Val1, COALESCE(Table2.Val2, 0) AS Val2
FROM Table1 LEFT OUTER JOIN Table2 USING (ID)

答案 1 :(得分:0)

LEFT JOINIFNULL()结合使用,为Val2填写零

SELECT 
  Table1.ID,
  Table1.Val1,
  IFNULL(Table2.Val2, 0) AS Val2
FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.ID

答案 2 :(得分:0)

SELECT Table1.ID, Table1.Val1, COALESCE(Table2.Val2, 0) AS Val2
FROM Table1 LEFT OUTER JOIN Table2 USING (ID)
INTO NewTable