2012-06-06 36 views
8

奇怪的事情发生了。我有安装在Windows NOT IN查询与我的MySQL社区服务器5.1中的问题。当我做这个查询:MySQL的 “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中的一个关键字尝试用反引号引用它 –

+2

'some_key'可以为null吗? –

+0

试试'where(date> =“2012-01-01”)和(key not in ...)'; MySQL的文档是含糊的'不in'操作和状态'EXPR NOT IN(值...)是一样的NOT(表达式IN(值,...))',这可能会导致'NOT( (日期> =“2012-01-01”和键)IN(...))'你的情况 – lanzz

回答

15

试试这个。

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 
+0

不错,他们都工作,似乎需要大约相同的时间。谢谢! –

+0

@jeffery_the_wind很乐意帮助你! –

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

最有可能你有你的 “钥匙” 列中的某些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);