SQL中in和not in

参考:http://www.cnblogs.com/seasons1987/archive/2013/07/03/3169356.html

今天遇到个问题,2W多条记录,使用in后是9k多,not in后竟然是空。就上网搜,就搜到了上面的连接,大概就是null值的原因吧!

还是来测试吧,例子也和连接的类似。

create table t1 (c1 int,c2 int);
go
create table t2 (c1 int,c2 int);
go
insert into t1 values(1,2),(1,3);
go
insert into t2 values(1,2);
go
image
select * from t1
where c2 in (select c2 from t2);
image
select * from t1
where c2 not in (select c2 from t2);
image
再往t2表中插入一条记录
insert into t2 values(1,null);
再次查询
select * from t1
where c2 in (select c2 from t2);
image
问题来了哦,看下面查询
select * from t1
where c2 not in (select c2 from t2);
image
select * from t1
where not exists (select c2 from t2 where t2.c2=t1.c2)
image
借用上文连接的那位仁兄的总结(直接ctrl+c,ctrl+v):

如果子查询中返回的任意一条记录含有空值,则查询将不返回任何记录。如果子查询字段有非空限制,这时可以使用not in,并且可以通过提示让它用hasg_aj或merge_aj连接。

如果查询语句使用了not in,那么对内外表都进行全表扫描,没有用到索引;而not exists的子查询依然能用到表上的索引。所以无论哪个表大,用not exists都比not in 要快。

原文地址:https://www.cnblogs.com/cnmarkao/p/4172057.html