我尝试执行以下查询,但没有得到任何数据,尽管它应该得到一个行:为什么[NOT IN]语法不起作用?
select * from [DB1.table1] where col1 not in (select col2 from DB2.table2)
COL1,COL2 VARCHAR类型
为什么它不工作?
我尝试执行以下查询,但没有得到任何数据,尽管它应该得到一个行:为什么[NOT IN]语法不起作用?
select * from [DB1.table1] where col1 not in (select col2 from DB2.table2)
COL1,COL2 VARCHAR类型
为什么它不工作?
“不起作用”对您的问题不是很好的描述,但在几乎所有情况下,这都是由子选择返回NULL值引起的。
你可能想这样的:
select * from [DB1.table1]
where col1 not in (select col2 from DB2.table2 where col2 is not null);
与NULL
比较总是产生“不确定”,因此如果至少一个排从子选择包含在col2
列NULL
整个表达式是“未定义”。由于未定义不是“真”,整个查询不会返回任何内容。
如果你有NULL
S IN col2
在table2
,你会得到你所描述的行为:
create table table2 (
col2 varchar(10) null
)
insert into table2 (col2) values ('abc'),(null)
create table table1 (
col1 varchar(10) null
)
insert into table1 (col1) values ('abc'),('def')
select * from table1 where col1 not in (select col2 from table2)
生成任何行。这是因为NOT IN
的结果变为UNKNOWN
,一旦发生NULL
比较。如果这是你的situtation正确的逻辑
select * from table1 where col1 not in (select col2 from table2 where col2 is not null)
:
您可以修复它。
正如其他人已经指出,造成这一问题的原因,你可以达到同样的效果,使用LEFT JOIN
它比谓词IN
与NULL
vlaues安全:
select t1.*
from [DB1.table1] AS T1
LEFT JOIN DB2.table2 AS t2 ON t1.col1 = t2.col2
where t1.col2 IS NULL;
COL1的类型= COL2?整理? – 2013-03-28 07:41:54
如果'col2'可为空且其中一行为* * * NULL,它将不返回行 - 但您没有给我们足够的信息以知道这是否是这种情况。 – 2013-03-28 07:42:25