in操作符:select * from 表A where 字段cc in (select cc from 表B);
not in操作符:select * from 表A where 字段cc not in (select cc from 表B); --最好不用not in
exists是对外表作loop循环,每次loop循环再对内表进行查询;not exists与之相反
select * from 表A where exists(select cc from 表B where cc=A.cc);
select * from 表A where not exists(select cc from 表B where cc=A.cc);
in与exists
如果查询的两个表大小相当,那么用in和exists差别不大;
如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in
not in与not exists
如果查询语句使用了not in,那么对内外表都进行全表扫描,没有用到索引;而not exists的子查询依然能用到表上的索引。
所以无论表大小,not exists都比not in快。
另外,not in逻辑上不完全等同于not exists,尽量使用not exists,用了not in程序可能会存在bug。
create table table_a(a1 int,a2 int);
insert into table_a values(1,2);
insert into table_a values(1,3);
create table table_b(b1 int,b2 int);
insert into table_b values(1,2);
insert into table_b values(1,null);
select * from table_a where a2 not in(select b2 from table_b); --执行结果:无
select * from table_a where not exists(select * from table_b where table_b.b2=table_a.a2); --执行结果:1 3
not in会调用子查询,not exists会调用关联子查询。
如果子查询中返回的任意一条记录中含有空值,则查询将不返回任何记录。如果子查询字段有非空限制,这时可以使用not in。