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

问题描述 投票:0回答:1

我有两张桌子

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
------------
postgresql
1个回答
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)    
© www.soinside.com 2019 - 2024. All rights reserved.