18

奇怪的事情发生了。我在 Windows NOT IN查询上安装的 MySQL Community Server 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 行

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

4

3 回答 3

31

试试这个。

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
于 2012-06-06T12:49:18.900 回答
14

很可能您的“键”列中有一些 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);
于 2012-06-06T12:50:01.357 回答
1
select * 
 from table1 
 where date >= "2012-01-01" 
 and `key` not in (select some_key from table2);
于 2012-06-06T12:49:13.063 回答