如何合并插入组合多个表

时间:2016-03-15 19:43:16

标签: mysql sql merge insert

我有多个表(每月12个),每个表有3列("代码"," test_name","值")

示例:

January
code | test_name | value
0001   name1       17
0002   name2       45
0005   name5       12
February
code | test_name | value
0001   name1       3
0002   name2       7
0004   name4       13
March
code | test_name | value
0001   name1       6
0006   name6       32
0007   name7       41

如何将它在sql中合并或插入或组合到一个如下所示的表中:

Year
code | test_name | January | February | March | ...
0001   name1       17        3          6
0002   name2       45        7          0
0003   name3       0         0          0
0004   name4       0         13         0
0005   name5       12        0          0
0006   name6       0         0          32
0007   name7       0         0          41

1 个答案:

答案 0 :(得分:0)

并行表(具有相同列的表)通常是设计不佳的标志。通常优选具有不同列的单个表。

您可以使用union allgroup by

执行您想要的操作
select code, test_name,
       max(jan) as jan, max(feb) as feb, max(mar) as mar
from ((select code, test_name, value as Jan, NULL as Feb, NULL as Mar
       from January
      ) union all
      (select code, test_name, NULL as Jan, value as Feb, NULL as Mar
       from February
      ) union all
      (select code, test_name, NULL as Jan, NULL as Feb, value as Mar
       from March
      )
     ) ct
group by code, test_name;