exists和in的查詢及效率比較

2021-08-31 14:15:11 字數 2174 閱讀 1032

有兩個簡單例子,以說明 「exists」和「in」的效率問題

sql**

1) select * from t1 where exists(select 1 from t2 where t1.a=t2.a) ;      

-- t1資料量小而t2資料量非常大時,t1<

2) select * from t1 where t1.a in

(select t2.a from t2) ;      

-- t1資料量非常大而t2資料量小時,t1>>t2 時,2) 的查詢效率高。 

1) select * from t1 where exists(select 1 from t2 where t1.a=t2.a) ;   

-- t1資料量小而t2資料量非常大時,t1<>t2 時,2) 的查詢效率高。

exists 用法:

請注意 1)句中的有顏色字型的部分 ,理解其含義;

其中 sql**

select 1 from t2 where t1.a=t2.a     

--相當於乙個關聯表查詢,相當於 

select 1 from t1,t2     where t1.a=t2.a   

select 1 from t2 where t1.a=t2.a  

--相當於乙個關聯表查詢,相當於

select 1 from t1,t2 where t1.a=t2.a

但是,如果你噹噹執行 1) 句括號裡的語句,是會報語法錯誤的,這也是使用exists需要注意的地方。

「exists(***)」就表示括號裡的語句能不能查出記錄,它要查的記錄是否存在。

因此「select 1」這裡的 「1」其實是無關緊要的,換成「*」也沒問題,它只在乎括號裡的資料能不能查詢出來,是否存在這樣的記錄,如果存在,這 1) 句的where 條件成立。

in 的用法:

繼續引用上面的例子

sql**

select * from t1 where t1.a in

(select t2.a from t2)  

select * from t1 where t1.a in (select t2.a from t2)
這裡的「in」後面括號裡的語句搜尋出來的字段的內容一定要相對應,一般來說,t1和t2這兩個表的a欄位表達的意義應該是一樣的,否則這樣查沒什麼意義。

打個比方:t1,t2表都有乙個字段,表示工單號,但是t1表示工單號的欄位名叫「ticketid」,t2則為「id」,但是其表達的意義是一樣的,而且資料格式也是一樣的。這時,用 2)的寫法就可以這樣:

sql**

select * from t1 where t1.ticketid in

(select t2.id from t2)      

select

name

from employee where

name

not in

(select

name

from student);      

select

name

from employee where

not exists (select

name

from student);   

select * from t1 where t1.ticketid in (select t2.id from t2)   

select name from employee where name not in (select name from student);

select name from employee where not exists (select name from student);

第一句sql語句的執行效率不如第二句。

通過使用exists,oracle會首先檢查主查詢,然後執行子查詢直到它找到第乙個匹配項,這就節省了時間。oracle在執行in子查詢時,首先執行子查詢,並將獲得的結果列表存放在乙個加了索引的臨時表中。在執行子查詢之前,系統先將主查詢掛起,待子查詢執行完畢,存放在臨時表中以後再執行主查詢。這也就是使用exists比使用in通常查詢速度快的原因。

mysql in 和exists查詢效率總結

看到網上好多的文章,關於in 和exists,我自己專門去校驗了一下,自己通過儲存過程,迴圈增加了10萬條資料,建立表 drop table if exists tb test create table tb test id int primary key auto increment not nu...

測試in 與exists 查詢效率

測試1w條資料和100w條資料下 in 和 exists的區別 t user 為100w條,t user memory 為1w條 1 in的原理 在select from a where id in select id from b 中,in 中的子查詢只執行一次,它查詢出b表中的所有id值並快取起...

關於EXISTS的使用及效率

本文參考了不過的oracle部落格http www.cnblogs.com yf520gn archive 2009 01 12 1374359.html 後根據自己的理解來寫的。建立兩張表t1 t2,其中t1的locline列中的某些值存在於t2的location中 create table t1...