两个键完全外部联接

时间:2019-12-05 05:37:06

标签: sql database postgresql full-outer-join

我正在尝试合并电话号码上的两个表,以便如果我在两个表中的任何一个中找到电话,则将其余字段合并,如下所示。 现在有些情况下,两个表中都不存在电话。然后,该表应在email_id上联接,因此基本上首先检查电话是否匹配(如果不匹配),然后检查电子邮件ID是否匹配。如果没有,则删除该记录。

strip_tags

但是我收到此错误

  

错误:仅在可合并合并或可哈希合并合并条件下支持FULL JOIN

     

SQL状态:0A000

有没有解决的办法,或者有更好的办法解决呢?

2 个答案:

答案 0 :(得分:0)

您可以合并左右连接的结果:

SELECT COALESCE(icici.phone, hsbc.phone) as phone,
    COALESCE(icici.email_id, hsbc.email_id) as email_id, city
FROM credit_card.icici
    LEFT OUTER JOIN credit_card.hsbc on icici.phone = hsbc.phone
                    OR icici.email_id = hsbc.email_id 
UNION (
    SELECT COALESCE(icici.phone, hsbc.phone) as phone,
        COALESCE(icici.email_id, hsbc.email_id) as email_id, city
    FROM credit_card.icici
        RIGHT OUTER JOIN credit_card.hsbc on icici.phone = hsbc.phone
                         OR icici.email_id = hsbc.email_id
    WHERE icici.id IS NULL
)

但是,右连接可能只包含找不到左表中任何值的行。例如,通过检查WHERE的主键,可以使用NULL过滤掉这些行。

答案 1 :(得分:0)

使用union all和聚合:

select phone, max(email_id)
       maxCOALESCE(icici.phone, hsbc.phone) as phone,
    COALESCE(icici.email_id, hsbc.email_id) as email_id, city
from ((select phone, email_id
       from credit_card.icici
      ) union all
      (select phone, email_id
       from credit_card.hsbc
      ) 
     ) cc
group by phone,
         (case when phone is null then email_id end);