[英]SQL Where not equal does not return NULL results
table 'materials'
id sku content
10 IT2 Iron
11 IT3 Steel
12 IT4 Steel
13 IT5 NULL
14 IT6 Iron
15 IT7 Glass
select id, sku, content from materials where content !='Iron';
Returns Result:返回结果:
id sku content
11 IT3 Steel
12 IT4 Steel
15 IT7 Glass
Why is id #13 with the NULL value not returned in the result set?为什么结果集中没有返回带有 NULL 值的 id #13? Using MYSQL.
使用 MYSQL。
As per your where
clause it compares null != 'Iron'
, which evaluates to UNKNOWN which neither true nor false based on SQL's 3 way logic.根据您的
where
子句,它比较null != 'Iron'
,根据 SQL 的 3 路逻辑,它的计算结果为 UNKNOWN 既不是真也不是假。 Hence it is not returned by the query.因此它不会由查询返回。
If you need the null
row to be resulted, you should use如果您需要产生
null
行,则应使用
where content !='Iron' or content is null
Edit: One more option is to use the relational null-safe equality operator <=>
with a negation.编辑:另一种选择是将关系空安全相等运算符
<=>
与否定一起使用。
not content <=> 'Iron'
From the documentation,从文档中,
NULL-safe equal.
NULL 安全的相等。 This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL.
此运算符执行与 = 运算符类似的相等比较,但如果两个操作数均为 NULL,则返回 1 而不是 NULL,如果一个操作数为 NULL,则返回 0 而不是 NULL。
The <=> operator is equivalent to the standard SQL IS NOT DISTINCT FROM operator.
<=> 运算符等效于标准 SQL IS NOT DISTINCT FROM 运算符。
mysql>
SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL
UNION
SELECT 1 = 1, NULL = NULL, 1 = NULL;
Returns退货
1 vs 1 | NULL vs NULL | 1 vs NULL | Comment
--------------------------------------------------
1 | 1 | 0 | for <=>
1 | NULL | NULL | for =
ISNULL(content, '') = 'Iron'
这会将 null 转换为空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.