在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);      

SQL中not in 和not exists

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

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

SQL中not in 和not exists

接着再用not exists。

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

SQL中not in 和not exists

 

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

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

相关文章:

  • 2022-12-23
  • 2021-06-06
  • 2022-12-23
  • 2022-01-19
  • 2022-12-23
  • 2022-03-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
  • 2021-10-14
  • 2021-11-23
  • 2021-10-24
  • 2022-12-23
相关资源
相似解决方案