In与Exist的区别

来源:互联网 发布:深圳软件产业基地 5e 编辑:程序博客网 时间:2024/06/17 11:50

In       ------ 遍历

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

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

 

本质区别:

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

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

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

使用环境:

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

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

e.g.:

In 的用法:

1Select Top10 ExpoName,ExpoClassID
2From tb_Expo
3Where ExpoClassIDin (SelectClassid From tb_Expo_Class Where ParentID=0)

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

等价于:

1Select Top10 a.ExpoName From tb_Expo a,
2(selectClassid from tb_expo_class where parentid=0) b
3Where a.ExpoClassID= b.ClassID

而Exist不同:

1select top10 ExpoName,ExpoClassID fromtb_Expo e
2where Exists (select0 from tb_expo_class where parentid=0)

其执行类似于下面的sql: 

01set   serveroutput on;
02declare
03        l_count  integer;
04begin
05        fortb_Expo  in (Select   ExpoName,ExpoClassID  From  tb_Expo)   loop
06                Selectcount(*) intol_count From tb_Expo_Class
07                whereparentid = 0
08 
09                if l_count != 0then
10                  dbms_output.put_line(e.ExpoName);
11                endif;
12 
13        endloop;
14end

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

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

如果

Select 0 from tb_expo_class where parentid=0

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