2016-06-11 60 views
1

中我确实有两个表表1表2。而且其内容如下当空值存在时,Mysql不返回任何值在子查询

mysql> select id from table1; 
+------+ 
| id | 
+------+ 
| 1 | 
| 2 | 
| 3 | 
| 4 | 
+------+ 
4 rows in set (0.00 sec) 

mysql> select id from table2; 
+------+ 
| id | 
+------+ 
| 301 | 
| 2 | 
| NULL | 
+------+ 
3 rows in set (0.00 sec) 

时,我打下面的查询在MySQL控制台,它总是返回空集

select id 
from table1 
where id 
not in (select id from table2); 

空集(0.00秒)

是否有一个原因,当在子查询中有空值不在会发生故障....?

我已经通过使用下面的查询

select id 
from table1 
where id 
not in (select id from table2 where id is not null); 
+------+ 
| id | 
+------+ 
| 1 | 
| 3 | 
| 4 | 
+------+ 

3行中集(0.00秒)

解决它只是想提前知道

谢谢:)

编辑:This question试图清除一些空气但不够

+0

可能重复[为什么MYSQL IN关键字不考虑NULL值](http://stackoverflow.com/questions/10810391/why-mysql-in-keyword-not-considering-null-values) –

+1

欢迎来到世界*三值逻辑*:https://en.wikipedia.org/wiki/Three-valued_logic#Application_in_SQL – dnoeth

回答

4

这就是not in的工作原理。我建议你使用not exists代替:

select id 
from table1 t1 
where not exists (select 1 from table2 t2 where t1.id = t2.id); 

为什么not in这种方式工作?这是因为not in的语义。请记住,SQL中的NULL(通常)表示未知的值。因此,如果你有一个“(1,2)”的列表,你可以说“3”不在列表中。如果你有“(1,2,未知)”你不能这么说。相反,结果是NULL,将其视为false。

NOT EXISTS不会这样做,所以我觉得使用起来更方便。