简体   繁体   English

仅存在一场比赛时的内部加入

[英]Inner Join when only one match exists

Consider the following realistic scenario: 请考虑以下现实情况:

You have a table of towns, but want to lookup the respective zip codes of those towns. 您有一张城镇表,但要查找这些城镇的邮政编码。 In most cases, this is easy to do since there is only one zip code per town, but exceptions do apply when dealing with cities. 在大多数情况下,这很容易做到,因为每个城镇只有一个邮政编码,但是在处理城市时确实有例外。

You have two tables: 您有两个表:

CONTACT
Town          | Zip
--------------+----
Ft Washington | NULL
Ambler        | NULL
Media         | NULL
Ambler        | NULL
New York      | NULL

CITIES_EXTENDED
Town          | Zip
--------------+----
Ft Washington | 19034
Ambler        | 19002
Media         | 19063
New York      | 10101
New York      | 10102
New York      | 10103
New York      | 10104

With an INNER JOIN four rows would be returned for the New York . 有了INNER JOIN四行将返回New York This is obviously not desirable because that data is inherently inaccurate. 这显然是不希望的,因为该数据本质上是不准确的。

The desired result is as follows: 预期结果如下:

Town          | Zip
--------------+----
Ft Washington | 19034
Ambler        | 19002
Media         | 19063
Ambler        | 19002
New York      | NULL

What is the best way of achieving this goal? 实现这个目标的最佳方法是什么?

Does this solve your problem? 这样可以解决您的问题吗?

select ce.Town, 
case when count(*) > 1 then null else Max(c.Zip) end as Zip
from CITIES_EXTENDED ce
    inner join CONTACT c
        on ce.Town = c.Town
    group by ce.Town

The Max() function will work just fine because you will only have one value for c.Zip. Max()函数可以正常工作,因为c.Zip只有一个值。

Try: 尝试:

Select  a.Town,
        b.zip
FROM    contact a
INNER JOIN cities_extended b ON a.Town = b.Town
WHERE a.Town NOT IN (
    SELECT  Town
    FROM    (
        Select  Town,
                COUNT(*)
        From    cities_extended
        Group by Town
        HAVING COUNT(*) > 1
    ) T
)

UNION ALL 

Select  DISTINCT
        a.Town,
        NULL
FROM    contact a
INNER JOIN  cities_extended b ON a.Town = b.Town
WHERE   a.Town IN (
    SELECT  Town
    FROM    (
        Select  Town,
                COUNT(*)
        From    cities_extended
        Group by Town
        HAVING COUNT(*) > 1
    ) T
)

See my Demo 看我的演示

This may not be an elegant solution but this gets the job done as per your requirement ;-) 这可能不是一个很好的解决方案,但是可以按照您的要求完成工作;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM