[英]Why doesn't SQL “NOT IN ('val1')” return if the field is null?
I have a query like this one: 我有一个像这样的查询:
Select *
FROM table1
WHERE field1 NOT IN ('value1')
If the field1
of the row is null
, it will not be returned. 如果行的
field1
为null
,则不会返回。 It doesn't look logical to me, because null
is not 'value1', so the row should be returned, this can cause many bugs. 它对我来说看起来不合逻辑,因为
null
不是'value1',所以应返回该行,这可能会导致许多错误。 I understand that it's working like that because of some reasons. 我明白,由于某些原因,它的工作方式如此。 What are they?
这些是什么?
A NULL
is not a value, in SQL. 在SQL中,
NULL
不是值。
SELECT NULL = NULL
# => NULL
SELECT NULL != NULL
# => NULL
Thus, 从而,
cause null is not 'value1'
原因null不是'value1'
but NULL
is also not not 'value1'. 但
NULL
也不是 'value1'。 NULL
is basically the SQL way of saying "I don't know". NULL
基本上就是说“我不知道”的SQL方式。 So it might be 'value1', or it might not. 所以它可能是'value1',或者它可能不是。 The way to test for
NULL
is 测试
NULL
是
SELECT NULL IS NULL;
# => 1
Thus, try this: 因此,试试这个:
WHERE field1 NOT IN ('value1') OR field1 IS NULL
to specifically address the case. 专门处理此案。
null
is not a value - it's the lack thereof. null
不是一个值 - 它缺乏价值。 Think of it as missing data. 将其视为缺失数据。 Whenever it participates in a logical operator that works on values (such as
in
), it's result is "unknown" - "Question: is a missing value one the the following values? Answer: I don't know". 每当它参与一个对值(例如
in
)起作用的逻辑运算符时,它的结果就是“未知” - “问题:以下值是缺失值吗?答案:我不知道”。
Since "unknown" ins't true, the row is not evaluated. 由于“未知”不正确,因此不评估该行。 If you want to handle
null
s you'd have to do so explicitly, eg, by using the in
operator: 如果要处理
null
必须明确地执行此操作,例如,使用in
运算符:
SELECT *
FROM table1
WHERE field1 IS NULL OR field1 NOT IN ('value1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.