SQL Exists的使用

1

if exists(select * from WebUser where username='liy01') 
	begin
		select top 10* from webuser --如果select * from WebUser where username='liy01'有数据则执行这
	end
else 
	begin
	
		select top 5 * from webuser --如果select * from WebUser where username='liy01'查询不到数据,则执行这里
	end

Exists与In的区别,以下两条语句效果一样

--当条件(select id from webuser where id<1000)里的数据量比较小的时候用in或者Exists效果差不多
select * from webuser where id in(select id from webuser where id<100)

--当条件(select id from webuser u where id<1000 and u.Id=w.id)里的数据量非常大的时候就用Exists
select * from webuser w where  Exists (select id from webuser u where id<100 and u.Id=w.id) --特别要注意u.Id=w.id 一定要加上

A: In:是把外表和内表做Hash 连接,而exists 是对外表作loop 循环,每次loop循环再对内表进行查询。
当查询两个表的大小相当时,用In 和 exists差别不大。
如果两个表中一个表较小,一个表较大,那么子查询表大的用exists,子查询表小的用In,效率会高的。
也就是说 IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况,这样效率会高的


例如 :表a(小表),表b(大表)

1》

select * from a where aid in (select aid from b) ---效率低:全程扫描b表,用到a 表上的aid的索引,因为a表小,b表大
 上面in的语句可以理解为:
select * from a, ( select distinct aid from b) b1
where a.aid = b1.aid.

select * from a where exists (select aid from b where b.aid = a.aid) ---效率高: 全程扫描a表,用到b表上的aid的索引。因为b表大。
上面的exists的语句可以理解为:
for aid in ( select * from a)
    loop
       if ( exists ( select aid from b where b.aid= a.aid )
    then 
       OUTPUT THE RECORD!
    end if
end loop

2》

select * from b where aid in (select aid from a)----效率高:全程扫描a 表,用到b表上的aid 索引
select * from b where exists (select aid from a were a.aid= b.aid) ---效率低:全程扫描b 表:用到a 表上的aid索引。

B: Not in 和Not Exists 的 效率
如果查询语句使用了Not In,那么内外表全部进行扫描,没有乃至索引
Not Exist用到子表中的索引进行查询,所以无论两个表中哪个表大,Not exists 都要比Not in 要快。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值