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

时间:2015-03-11 20:39:05

标签: mysql sql-server left-join

我有两个表,CustomerscustomerTowns。我想将城镇名称存储在customerTowns中,并从townID

中存储的Customers链接到该名称

|Customers| |townID |

|customerTowns| |townID | |townName |

我的sql如下,

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

这几乎返回了我正在寻找的结果。除此之外,我希望townID中的每个条目都重复customerTowns

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

我觉得我必须亲近,只是想弄清楚如何只返回一行,或者为什么它返回多行!

我想要的输出是;

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

2 个答案:

答案 0 :(得分:2)

使用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;

答案 1 :(得分:1)

执行此操作的最有效方法可能是使用exists

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

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

的查询效果更好