通过查看MySql合并2记录集

时间:2017-11-09 09:30:33

标签: mysql sql

我有两个记录集,第一个:

ID Field1 Field2  Field3  Field4  
 1   aa1    bb1    cc1     NULL
 2   aa2    bb2    cc2     NULL   

第二个:

ID Field1 Field2  Field3   Field4  
 1   aa1    bb1    NULL     dd1
 2   aa2    bb2    NULL     dd2 

我想创建一个合并两者的视图,以便将相同的键分组在同一行中,我想得到:

ID Field1 Field2  Field3   Field4  
 1   aa1    bb1    cc1      dd1
 2   aa2    bb2    cc2      dd2 

我尝试了这段代码,但没有得到希望的结果:

SELECT * FROM (
SELECT
    t.ID,
    t.Field1,
    t.Field2,
    t.Field3,
    NULL as 'Field4'
FROM TABLE
WHERE ...

UNION ALL

SELECT
    t.ID,
    t.Field1,
    t.Field2,
    NULL as 'Field3',
    t.Field4
FROM TABLE
WHERE ...

) GROUP BY ID, Field1, Field2

1 个答案:

答案 0 :(得分:0)

试试这个答案,我希望这会对你有所帮助:

SELECT COALESCE(T1.ID,T2.ID)ID
    ,COALESCE(T1.Field1,T2.Field1)Field1
    ,COALESCE(T1.Field2,T2.Field2)Field2
    ,COALESCE(T1.Field3,T2.Field3)Field3
    ,COALESCE(T1.Field4,T2.Field4)Field4
from Table1 T1
INNER JOIN Table2 T2 ON T1.ID=T2.ID