问题描述
如果查询/子查询没有找到任何匹配的行,那么它要么返回 NULL,要么根本不返回值,因此甚至不返回 NULL 值.基于查询/子查询返回 NULL 的条件是什么?什么时候不返回任何结果,甚至不返回 NULL 值?
If a query/subquery doesn’t find any matching rows, then it either returns NULL or no value at all, thus not even a NULL value. Based on what criteria does a query/subquery return a NULL and when doesn’t it return any results, not even a NULL value?
如果没有,标量子查询是否总是返回 NULL找到匹配的行?我假设最外部的标量查询也返回如果没有找到行,则为 NULL?
Will a scalar subquery always return NULL, when no matching rows are found? I assume most-outer scalar query also returns NULL if no rows are found?
SELECT FirstName, LastName, YEAR(BirthDate)
FROM Persons
WHERE YEAR(BirthDate) IN (SELECT YearReleased FROM Albums);
如果子查询没有找到结果,就是外层的WHERE子句查询翻译成
WHERE YEAR(BirthDate) IN (null);
?如果 WHERE 子句被翻译成
WHERE YEAR(BirthDate) IN();
,那不应该是一个错误条件,因为YEAR(BirthDate)
值比什么都没有?If WHERE clause is translated into
WHERE YEAR(BirthDate) IN();
instead, shouldn’t that be an error condition, since how canYEAR(BirthDate)
value be compared to nothing?推荐答案
只有当
YearReleased
为NULL
时,子查询才会返回NULL
,否则将有一个空记录集,使其成为您提到的IN ()
案例.The subquery would only ever return
NULL
whenYearReleased
wasNULL
, otherwise there would be an empty recordset, making it theIN ()
case you mentioned.区分两者非常重要,因为它们的含义完全不同.
NULL
表示有一些东西需要SELECT
ed,尽管该值可以说是缺乏价值".空记录集表示没有任何符合指定条件的选择.It's very important to distinguish between the two as they mean entirely different things.
NULL
indicates that there was something to beSELECT
ed, although that value indicates a "lack of value" so to speak. An empty recordset indicates that there was nothing to be selected that matched the criteria specified.编辑:更新以显示示例结果
前两个查询只是为了显示两个表中的内容.第三个查询是您的查询,而第四个查询只是显示如果您将子查询替换为
NULL
,它会产生等效结果(无行).最后一个查询只是为了表明子查询本身只是返回一个NULL
的大列表.First two queries are just to show what's in the two tables. Third query is your query and the fourth query just shows that it produces an equivalent result (no rows) if you replace the subquery with a
NULL
. Last query is just to show that the subquery itself just returns a big list ofNULL
s.这篇关于查询/子查询什么时候返回 NULL,什么时候根本没有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!