
[英]mySQL select query does not return results when using a WHERE clause against a NULL column.
[英]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';
返回结果:
id sku content
11 IT3 Steel
12 IT4 Steel
15 IT7 Glass
为什么结果集中没有返回带有 NULL 值的 id #13? 使用 MYSQL。
根据您的where
子句,它比较null != 'Iron'
,根据 SQL 的 3 路逻辑,它的计算结果为 UNKNOWN 既不是真也不是假。 因此它不会由查询返回。
如果您需要产生null
行,则应使用
where content !='Iron' or content is null
编辑:另一种选择是将关系空安全相等运算符<=>
与否定一起使用。
not content <=> 'Iron'
从文档中,
NULL 安全的相等。 此运算符执行与 = 运算符类似的相等比较,但如果两个操作数均为 NULL,则返回 1 而不是 NULL,如果一个操作数为 NULL,则返回 0 而不是 NULL。
<=> 运算符等效于标准 SQL IS NOT DISTINCT FROM 运算符。
mysql>
SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL
UNION
SELECT 1 = 1, NULL = NULL, 1 = NULL;
退货
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.