SQLBolt.com - 第 8 课第 2 题的备选答案
SQLBolt.com - Alternative Answer to Lesson 8, Q2
我从 https://sqlbolt.com/lesson/select_queries_with_nulls
得到第 8 课第二个问题的替代答案
Find the names of the buildings that hold no employees
我的尝试是:
SELECT building_name FROM buildings WHERE building_name NOT IN(SELECT DISTINCT(building) FROM employees);
它没有返回我的正确答案并且更喜欢答案 SELECT building_name FROM buildings LEFT JOIN employees ON building_name = building WHERE name IS NULL
如果我做错了请告诉我。我不认为这里需要加入。谢谢
你没有犯“错误”。但是你的查询还有两个问题
首先,select distinct
完全没有必要。 IN
/NOT IN
会注意这一点——他们会忽略重复项。
更重要的是,NOT IN
并不像大多数人期望的那样使用 NULL
值——如果子查询中的任何值为 NULL
,则不会返回任何结果 完全。如果 employees
table 在 building
中没有 NULL
值,那么您的版本应该可以正常工作。
出于这个原因,我强烈建议您始终将 NOT EXISTS
与子查询一起使用:
SELECT b.building_name
FROM buildings b
WHERE NOT EXISTS (SELECT 1
FROM employees e
WHERE b.building_name = e.building
);
LEFT JOIN
版本在功能上等同于此版本。
我从 https://sqlbolt.com/lesson/select_queries_with_nulls
得到第 8 课第二个问题的替代答案Find the names of the buildings that hold no employees
我的尝试是:
SELECT building_name FROM buildings WHERE building_name NOT IN(SELECT DISTINCT(building) FROM employees);
它没有返回我的正确答案并且更喜欢答案 SELECT building_name FROM buildings LEFT JOIN employees ON building_name = building WHERE name IS NULL
如果我做错了请告诉我。我不认为这里需要加入。谢谢
你没有犯“错误”。但是你的查询还有两个问题
首先,select distinct
完全没有必要。 IN
/NOT IN
会注意这一点——他们会忽略重复项。
更重要的是,NOT IN
并不像大多数人期望的那样使用 NULL
值——如果子查询中的任何值为 NULL
,则不会返回任何结果 完全。如果 employees
table 在 building
中没有 NULL
值,那么您的版本应该可以正常工作。
出于这个原因,我强烈建议您始终将 NOT EXISTS
与子查询一起使用:
SELECT b.building_name
FROM buildings b
WHERE NOT EXISTS (SELECT 1
FROM employees e
WHERE b.building_name = e.building
);
LEFT JOIN
版本在功能上等同于此版本。