常用的SQL语句(三) - In与Exist的区别

本文详细对比了SQL查询中In与Exists两种操作符的区别,包括它们的执行方式、效率及适用场景,并通过具体示例说明了如何选择合适的操作符以提高查询性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In       ------ 遍历

Exists ------- 检索到满足条件即退出

Not Exists --------检索到不满足条件即退出

 

本质区别:

Exists 由于Exist属于外驱动,故会利用索引来检索数据

In 则属于内驱动 故不能利用索引检索数据

其中,In和Not In类似全表扫描,效率低,一般用 Exist和NotExist代替其用法。

使用环境:

*Exists 使用外连接查询时用到。

*In    使用内连接查询时用到。

e.g.:

In 的用法:

Select Top 10 ExpoName,ExpoClassID 
From tb_Expo
Where ExpoClassID in (Select Classid From tb_Expo_Class Where ParentID=0)

其中,先执行 Select Classid From tb_Expo_Class Where ParentID=0

等价于:

Select Top 10 a.ExpoName From tb_Expo a,
(select Classid from tb_expo_class where parentid=0) b
Where a.ExpoClassID= b.ClassID

而Exist不同:

select top 10 ExpoName,ExpoClassID from tb_Expo e
where Exists (select 0 from tb_expo_class where parentid=0)

其执行类似于下面的sql: 

set   serveroutput  on;
declare
        l_count   integer;
begin
        for tb_Expo  in (Select   ExpoName,ExpoClassID   From  tb_Expo)   loop
                Select count(*) into l_count From tb_Expo_Class
                where parentid = 0

                if l_count != 0 then
                  dbms_output.put_line(e.ExpoName);
                end if;

        end loop;
end

在查询数据量大的时候就会体现出效率来。

当然,也不能说Exist就比In好。

如果

Select 0 from tb_expo_class where parentid=0

查询出来的数据量很少的话,还是 In 效率更高些。

 

 

转载于:https://www.cnblogs.com/cancer_xu/archive/2011/02/24/1963619.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值