In與Exist的區別

來源:互聯網
上載者:User

In       ------ 遍曆

Exists ------- 檢索到滿足條件即退出

Not Exists --------檢索到不滿足條件即退出

 

本質區別:

Exists 由於Exist屬於外驅動,故會利用索引來檢索資料

In 則屬於內驅動 故不能利用索引檢索資料

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

使用環境:

*Exists 使用外串連查詢時用到。

*In    使用內串連查詢時用到。

e.g.:

In
的用法:

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

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

等價於:

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

而Exist不同:

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

其執行類似於下面的sql: 

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

在查詢資料量大的時候就會體現出效率來。

當然,也不能說Exist就比In好。

如果

Select 0 from tb_expo_class where parentid=0

查詢出來的資料量很少的話,還是 In 效率更高些。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.