MySQL“NOT IN”无法正常工作

时间:2012-06-06 12:45:52

标签: mysql notin

发生了奇怪的事情。我在Windows NOT IN 查询中安装了MySQL社区服务器5.1时出现问题。当我这样做时:

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行

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

3 个答案:

答案 0 :(得分:19)

试试这个。

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

或使用不存在

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

答案 1 :(得分:8)

您的“密钥”列中很可能有一些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);

答案 2 :(得分:1)

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