Mysql联合,获取2个信息

时间:2016-04-13 07:52:56

标签: mysql sql

我有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

谢谢

3 个答案:

答案 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

SQL Fiddle

支持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