SQL语句:in、not in与exists、not exists的区别

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。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值