查询结果中不包含 NULL 值
考虑下表:
create table inttest (
someint INT(10) NULL DEFAULT NULL
);
当我插入一些随机值
insert into inttest
(someint)
values
(1),(2),(3),(1),(2),(NULL);
并执行查询
select *
from inttest
where someint != 1;
时,MySQL 返回 2,3,2 但不是 NULL 值。这是正确的吗?我应该使用 OR someint IS NULL 扩展我的查询还是这是我的 MySQL 安装中的错误?
Considering the following table:
create table inttest (
someint INT(10) NULL DEFAULT NULL
);
When I insert some random values
insert into inttest
(someint)
values
(1),(2),(3),(1),(2),(NULL);
and execute the query
select *
from inttest
where someint != 1;
MySQL returns 2,3,2 but not the NULL value. Is this correct? Should I extend my query with OR someint IS NULL or is it a bug in my MySQL installation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正确的。没有任何东西等于
NULL
- 包括NULL
。或者更正式地说,计算NULL != 1
的结果是UNKNOWN
- 并且WHERE
子句谓词必须计算为TRUE.
Correct. Nothing is equal to
NULL
- includingNULL
. Or more formally, the result of evaluatingNULL != 1
isUNKNOWN
- andWHERE
clause predicates have to evaluate toTRUE
.比较运算符返回
TRUE
、FALSE
或NULL
。您期望
NULL != 1
为您提供TRUE
,但明智的是,您进行的比较会得到NULL
。这是因为与NULL
进行比较是没有意义的:NULL
不是一个值!。这里有一个狡猾的技巧,如果您确实想要的话,可以在结果集中获取
NULL
。这个技巧依赖于反转逻辑,然后手动排除 NULL 的可能性:更明显的方法可能是:
Comparison operators return
TRUE
,FALSE
orNULL
.You're expecting
NULL != 1
to give youTRUE
but, sensibly, you getNULL
for the comparison you make. This is because comparing anything withNULL
is meaningless:NULL
is not a value!.Here's a cunning trick whereby you could get the
NULL
in the resultset if you still really want it. The trick relies on reversing the logic, then manually excluding theNULL
possibility:A more obvious approach might be:
您必须将 NULL 视为未知的意思。
在您的具体情况下,
someint <> 1
,您要求 SQL 引擎过滤掉任何不是 1 的内容。由于 NULL 是未知的,因此它可能是 1,但我们永远不会知道。因此,SQL 引擎不会包含它,因为它不确定它不是 1。You have to think of NULL as meaning UNKNOWN.
In your specific case,
someint <> 1
, you are asking the SQL engine to filter out anything that is not a 1. Since NULL is UNKNOWN, it could be a 1 but we will never know. Because of this, the SQL engine won't include it because it's not sure that it's not a 1.