LEFT JOIN 表和右边不存在的空值

LEFT JOIN tables and null values that dont exist in the right

我有两个表,CustomerscustomerTowns。我想将 customerTowns 中的城镇名称和 link 中的 townID 存储在 Customers

|Customers| |townID |

|customerTowns| |townID | |townName |

而我的sql如下,

SELECT townName, Customers.townID
FROM customerTowns
LEFT OUTER JOIN Customers
ON Customers.townID = customerTowns.townID

这几乎是我要找的 return 的结果。除了,我希望 customerTowns 中的每个条目都重复 townID

|townName |townID| |London |1 | |London |1 | |London |1 | |London |1 | |London |1 | |Manchester|NULL | |Liverpool |NULL |

我觉得我一定很接近,只是不知道如何 return 只是一行,或者为什么它 return 多行!

我想要的输出是;

|townName |townID| |London |1 | |Manchester|NULL | |Liverpool |NULL |

使用 group by 或 distinct。

SELECT townName, Customers.townID
FROM customerTowns
LEFT OUTER JOIN Customers
ON Customers.townID = customerTowns.townID
GROUP BY townName, Customers.townID;

SELECT DISTINCT townName, Customers.townID
FROM customerTowns
LEFT OUTER JOIN Customers
ON Customers.townID = customerTowns.townID;

最有效的方法可能是使用 exists:

SELECT ct.townName, 
       (exists (select 1 from Customers c where c.townID = ct.townId))
FROM customerTowns ct;

您的原始查询返回重复项的原因是 returns 每个客户一行。因为您的联接在两个表中都位于 TownId 上,所以您实际上只需要查看该城镇是否存在客户。这应该比需要 distinctgroup by.

的查询执行得更好