在SQL中连接两个具有相同行的表

时间:2017-06-07 13:22:46

标签: python sql

假设我有两个这样的表:

table 1:               table 2:
id      city           id      heading
1201     X             1201     A
1202     Y             1201     B
1203     Z             1202     C
1204     U             1202     D
                       1204     F

我想要像这样输出:

id  city id  heading
1201 X   1201  A
*null*   1201  B
1202 Y   1202  C
*null*   1202  D
1203 Z   *null*
1204 U   1204 F

请帮助我。

如果可能的话,Python也是可以接受的。

2 个答案:

答案 0 :(得分:1)

您正在寻找full outer join

SELECT * FROM table1 FULL OUTER JOIN table2 on table1.id=table2.id

答案 1 :(得分:0)

可以使用FULL OUTER JOIN,但您还需要一个序列号:

select t1.*, t2.*
from (select t1.*,
             row_number() over (partition by id order by id) as seqnum
      from table1 t1
     ) t1 full outer join
     (select t2.*,
             row_number() over (partition by id order by id) as seqnum
      from table2 t2
     ) t2
     on t1.id = t2.id and t1.seqnum = t2.seqnum;