我有2张桌子
表1:
T1ID, Info
1,A
2,B
3,C
表2
T2ID, Info
1,D
2,E
3,F
现在我希望将这些结合起来与以下结果
T1ID,T2ID,Info
1,null,A
2,null,B
3,null,C
null,1,D
null,2,E
null,3,F
谢谢
答案 0 :(得分:2)
select T1ID, null as T2ID, Info from T1
union all
select null as T1ID, T2ID, Info from T2
答案 1 :(得分:0)
只需使用:
select T1ID,null,Info from table1
Union
select null,T2ID,Info from table2
答案 2 :(得分:0)
您也可以通过模拟FULL OUTER JOIN
来执行此操作,以避免在查询中指定null
:
SELECT T1ID, T2ID, T1.INFO AS INFO
FROM TABLE1 T1 LEFT JOIN TABLE2 T2 ON T1.INFO=T2.INFO
UNION ALL
SELECT T1ID, T2ID, T2.INFO AS INFO
FROM TABLE1 T1 RIGHT JOIN TABLE2 T2 ON T1.INFO=T2.INFO
支持FULL OUTER JOIN
会更简单:
SELECT T1ID, T2ID, COALESCE(T1.INFO, T2.INFO) AS INFO
FROM TABLE1 T1 FULL OUTER JOIN TABLE2 T2 ON T1.INFO=T2.INFO