【问题标题】:How to join two tables NULL filling attributes that aren't related to other table如何连接两个表 NULL 填充与其他表无关的属性
【发布时间】:2020-11-21 11:28:15
【问题描述】:

嘿,我想加入两个表

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 不相交。 有没有办法像示例代码中描述的那样,专门填充与该表无关的列?

【问题讨论】:

    标签: sql postgresql inner-join union


    【解决方案1】:

    你似乎想要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
    

    【讨论】:

    • 谢谢!第一个就是我要找的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    相关资源
    最近更新 更多