【问题标题】:How to join table with both equal and Not equal on same column如何在同一列上连接相等和不相等的表
【发布时间】:2019-11-14 10:37:25
【问题描述】:

我有两张如下表

表A:

id   Country
----------
1     US
----------
2     SG
----------
3     EU
----------
4     IN 

表B:

Report   country
----------------
No       NOT US
---------------
Yes      US

需要的输出如下:

TableA.id   TableA.Country  TableB.country TableB.Report
--------------------------------------------------------
1            US                  US           Yes
--------------------------------------------------------
2            SG                NOT US          NO
-------------------------------------------------------
3            EU                NOT US          NO
---------------------------------------------------------
4            IN                NOT US          NO

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql join


【解决方案1】:

使用左连接

select id,a.Country,coalesce(b.country,'NOT US') as Bcountry,
       coalesce(Report,'NO') as report
from tableA a left join tableB b on a.country=b.country 

【讨论】:

    【解决方案2】:

    你可以有复杂的join条件:

    select a.*, b.*
    from a join
         b
         on (a.country = 'US' and b.country = 'US') or
            (a.country <> 'US' and b.country = 'NOT US') ;
    

    or 在查询中通常是性能杀手。通常,这种类型的查询用于匹配默认值。在这种情况下,一种技术是两个left joins:

    select a.*,
           coalesce(b.country, bdef.country) as b_country,
           coalesce(b.report, bdef.report) as b_report
    from a join
         b
         on a.country = b.country left join
         b bdef
         on b.country is null and
            bdef.country = 'NOT US'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-13
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      相关资源
      最近更新 更多