合并表并保留所有不同的ID值

时间:2016-07-19 21:35:12

标签: mysql

我有多个要合并的表,这些表可能有不同的ID值。

例如:

表1:

ID Year Month Size1
A  2015   4    10
B  2015   5    20

表2:

ID Year Month Size2
A  2015   4    20
C  2015   5    40

表3:

ID Year Month Size3
D  2015   6    50
E  2015   7    50

我希望合并的表看起来像这样:

ID Year Month Size1 Size2 Size3
A  2015   4     10    20   NULL
B  2015   5     20   NULL  NULL
C  2015   5    NULL   40   NULL
D  2015   6    NULL  NULL  50
E  2015   7    NULL  NULL  50

我希望输出ID列包含所有表中的所有不同ID。 我的猜测是,这可以通过使用Full Outer Join On ID以某种方式实现,但我不能完全生成所需的输出格式。

2 个答案:

答案 0 :(得分:0)

select t1.id, t1.year, t1.month, t1.size1, t2.size2, t3.size3 
from table1 as t1
left outer join table2 as t2 on t1.id = t2.id and t1.year = t2.year and t1.month = t2.month
left outer join table3 as t3 on t1.id = t3.id and t1.year = t3.year and t1.month = t3.month
union
select t3.id, t3.year, t3.month, t1.size1, t2.size2, t3.size3 
from table3 as t3
left outer join table1 as t1 on t3.id = t1.id and t3.year = t1.year and t3.month = t1.month
left outer join table2 as t2 on t3.id = t2.id and t3.year = t2.year and t3.month = t2.month

答案 1 :(得分:0)

这是另一个可能会显示结果的查询:

SELECT t.id, t.year, t.month, 
  SUM(size1) AS size1, SUM(size2) AS size2, SUM(size3) AS size3 
FROM (
  SELECT id, year, month, size1, NULL AS size2, NULL AS size3 FROM t1
  UNION ALL
  SELECT id, year, month, NULL, size2, NULL FROM t2
  UNION ALL
  SELECT id, year, month, NULL, NULL, size3 FROM t3
) AS t
GROUP BY t.id, t.year, t.month;