SQL中not in 和not exists

在SQL中倒是经常会用到子查询,而说到子查询,一般用的是in而不是exists,先不谈效率问题,就先说说会遇到哪些问题。

用到in当取反的时候,肯定先想到的就是not in。但是在使用not in的时候的确会出现数据上的错误。下面看一个例子

create table #t1(c1 int,c2 int);   --创建表t1

create table #t2(c1 int,c2 int);   --创建表t2

insert into #t1 values(1,2);

insert into #t1 values(1,3);

insert into #t2 values(1,2);

insert into #t2 values(1,null);      

此时表数据就是这样,进行数据查询先用not in。

select * from #t1 where c2 not in(select c2 from #t2); --结果是0条数据

接着再用not exists。

select * from #t1 where not exists(select 1 from #t2 where #t2.c2=#t1.c2)--结果是1条数据

正如所看到的,not in出现了不期望的结果集,存在逻辑错误,以前没发现这种问题。

这个是个小实验,参照文章。http://www.cnblogs.com/seasons1987/archive/2013/07/03/3169356.html

原文地址:https://www.cnblogs.com/sdadx/p/6379471.html