我有两个桌子-

1:

col_1        col_2        col_3
10001        apple        3
10001        orange       2
10001        grapes       5


2:

col_1        col_2        col_3        col_4
10001        apple        3            123
10001        orange       2            345


什么SQL查询将连接这两个表;给我这样的结果:

col_1        col_2        col_3        col_4
10001        apple        3            123
10001        orange       2            345
10001        grapes       5

最佳答案

连接表,然后使用COALESCE获取第一个非空数据列

SELECT COALESCE(t1.col_1,t2.col_1) col_1,
   COALESCE(t1.col_2,t2.col_2) col_2,
   COALESCE(t1.col_3,t2.col_3) col_3,
   COALESCE(t2.col_4,'') col_4,
FROM t1
FULL JOIN t2 ON t1 ON t1.col_1 = t2.col1 AND t1.col_2 = t2.col_2 AND t1.col_3 = t2.col_3

07-26 06:49