postgres查找匹配和不匹配的记录

时间:2018-07-24 09:01:19

标签: postgresql

我有两个桌子

offline_tbl

cen | subcen
------------
01  | 002 
------------
02  | 001 
------------
02  | 003 
------------
03  | 001 
------------
03  | 009 
------------

online_tbl

cen | subcen
------------
01  | 002 
------------
02  | 001 
------------
02  | 004
------------
03  | 001 
------------
03  | 008
------------
04  | 079
------------
05  | 006
------------

我有两个表offline_tblonline_tbl。我想将offline_tbl censubcenonline_tbl censubcen匹配。

offline_tblonline_tbl中存在但不在两个表中都存在的记录。

我的预期输出

cen | subcen
------------
02  | 003 
------------
02  | 004 
------------
03  | 008
------------
03  | 009 
------------
04  | 079
------------
05  | 006
------------

1 个答案:

答案 0 :(得分:1)

使用完全连接:

select 
    a.cen as offline_cen, 
    a.subcen as offline_subcen, 
    b.cen as online_cen, 
    b.subcen as online_subcen
from offline_tbl a
full join online_tbl b 
on a.cen = b.cen and a.subcen = b.subcen

 offline_cen | offline_subcen | online_cen | online_subcen 
-------------+----------------+------------+---------------
 01          | 002            | 01         | 002
 02          | 001            | 02         | 001
 02          | 003            |            | 
             |                | 02         | 004
 03          | 001            | 03         | 001
             |                | 03         | 008
 03          | 009            |            | 
             |                | 04         | 079
             |                | 05         | 006
(9 rows)

如果只想获取其中一个表中的值:

select 
    coalesce(a.cen, b.cen) as cen, 
    coalesce(a.subcen, b.subcen) as subcen
from offline_tbl a
full join online_tbl b 
on a.cen = b.cen and a.subcen = b.subcen
where a.cen is null or b.cen is null

 cen | subcen 
-----+--------
 02  | 003
 02  | 004
 03  | 008
 03  | 009
 04  | 079
 05  | 006
(6 rows)