当NOT IN内部查询包含值'NULL'时,为什么结果集为EMPTY?

时间:2018-12-05 09:22:01

标签: mysql sql

这是我的名为samp的mysql表

+--------+--------+
| name   | roleid |
+--------+--------+
| alki   |      2 |
| karthi |      3 |
| aadhil |      2 |
| pri    |      2 |
| pri    |      2 |
+--------+--------+

当我使用类似select name from samp where name not in ('alki','pri',NULL)的查询

我希望结果是

+--------+
| name   |
+--------+
| karthi |
| aadhil |
+--------+

但是我的结果是Empty set。我有另一种选择。但是我需要知道其背后的原因。

4 个答案:

答案 0 :(得分:3)

您可以在下面尝试

select name from samp where name not in ('alki','pri') and name is not null

答案 1 :(得分:3)

NULL表示未知,它不是一个值,您需要使用not null而不是在NULL

中使用

您可以尝试一下。

select name from samp where name not in ('alki','pri') and name is not null

答案 2 :(得分:3)

您可以简单地做到:

select name
from samp
where name not in ('alki', 'pri');

NULL失败not in,就像其他大多数比较失败一样。

如果您明确想包含NULL,则需要将其包含为:

select name
from samp
where name not in ('alki', 'pri') or name is null;

答案 3 :(得分:1)

这就是NULL的行为方式。它在设计上无法与任何东西进行比较。您的查询的解释如下:

select name
from samp
where name <> 'alki'
and name <> 'pri'
and name <> NULL

由于name都不等于“不”等于NULL,因此不满足条件。