如何连接两个 tables 与其他 table 无关的 NULL 填充属性

How to join two tables NULL filling attributes that aren't related to other table

嘿,我正在尝试加入两个 table

Table1
M  N  a3
--------
3  a  W
3  b  Q
3  c  W
3  d  Q

Table2
M  N  a4
--------
3  e  M
3  f  K
3  g  K
3  h  M

我要:

Result:
M  N  a3 a4
-----------
3  a  W  ∅ 
3  b  Q  ∅
3  c  W  ∅
3  d  Q  ∅
3  e  ∅  M
3  f  ∅  K
3  g  ∅  K 
3  h  ∅  M

我试过了:

select M, N, a3, a4
from Table1 t1
join Table2 t2 on (t1.M = t2.M and t1.N = t2.N)

我试过了,但它给了我一个空集,因为 T1 中的 N 与 T2 中的 N 不相交。 有没有一种方法可以空填充与 table 无关的列,具体就像示例代码中描述的那样?

你似乎想要union all:

select m, n, a3, null as a4 from table1
union all select m, n, null, a4 from table2

如果两个表之间有 (m, n) 个共同的元组,并且您希望它们在结果集中的一行中,那么它有点不同。你可以 full join:

select coalesce(t1.m, t2.m) as m, coalesce(t1.n, t2.n) as n, t1.a3, t2.a4
from table1 t1
full join table2 t2 on t2.m = t1.m and t2.n = t1.n