MySQL中的“NOT IN”无法正常工作

18

奇怪的事情发生了。我在Windows上安装了MySQL Community Server 5.1,出现了一个问题,涉及到NOT IN查询。当我执行以下查询时:

select * 
  from table1 
  where date >= "2012-01-01";

返回582行

select * 
  from table1 
  where date >= "2012-01-01" 
    and the_key in (select some_key from table2);

返回 15 行

因此我期望以下查询将返回 582 - 15 = 567 行

select * 
 from table1 
 where date >= "2012-01-01" 
 and the_key not in (select some_key from table2);

返回0行

为什么最后一个查询没有返回任何行?


1
"key" 是 SQL 中的关键字,请尝试使用反引号进行引用。 - Mihai Stancu
尝试使用 where (date >= "2012-01-01") and (key not in ...);MySQL文档对于 not in 运算符并不明确,并且说明 expr NOT IN (value,...)NOT (expr IN (value,...)) 相同,这可能会导致在您的情况下出现 NOT((date >= "2012-01-01" and key) IN (...)) - lanzz
是的,某些关键字可以为空,有时确实为空。 - jeffery_the_wind
6
如果子查询返回null(在你的情况下,如果some_key是null),那么“not in”子句将无法工作。过滤子查询,使得some_key不为null。 - AdityaKapreShrewsburyBoston
"not in" 不起作用。为什么?这是一个错误吗? - Vahid2015
3个回答

32

试试这个。

select * 
 from table1 
 where date >= "2012-01-01" 
 and `key` not in (select some_key from table2 where some_key is not null);

或者使用not exists

 select * 
 from table1 
 where date >= "2012-01-01" and not exists ( select some_key from table2 where table2.some_key = table1.key

不错,它们都能正常工作且看起来需要大致相同的时间。谢谢! - jeffery_the_wind
我本来想为这个答案点赞,但它只提供了一些原始方法的替代方案。它没有解释为什么原始方法不起作用。@Kibbee的回答解释了问题所在。 - Syntax Junkie

18

很可能在你的“key”列中有一些NULL值。NULL比较总是返回null,它被评估为false。这可能会令人困惑。例如:

SELECT * FROM MyTable WHERE SomeValue <> 0 

不会返回SomeValue = NULL的值。尽管从直觉上来看,NULL并不等于零。所以要修复你的查询,你应该做以下操作。

select * from table1 where date >= "2012-01-01" 
and (key not in (select some_key from table2) OR key IS NULL);

在我的情况下,not in array 查询中也存在空值。谢谢。 - Irakli

1
select * 
 from table1 
 where date >= "2012-01-01" 
 and `key` not in (select some_key from table2);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接