SQL查詢中in和exists的區別分析

2021-09-29 13:09:42 字數 1134 閱讀 2179

假設表a表示某企業的員工表,表b表示部門表,查詢所有部門的所有員工,很容易有以下sql:

select * from a where deptid in (select deptid from b);

這樣寫等價於:

先查詢部門表b

select deptid from b

再由部門deptid,查詢a的員工

select * from a where a.deptid = b.deptid

可以抽象成這樣的乙個迴圈:

list<> resultset ;

for(int i=0;ifor(int j=0;jif(a[i].id==b[j].id) {

resultset.add(a[i]);

break;

顯然,除了使用in,我們也可以用exists實現一樣的查詢功能,如下:

select * from a where exists (select 1 from b where a.deptid = b.deptid);

因為exists查詢的理解就是,先執行主查詢,獲得資料後,再放到子查詢中做條件驗證,根據驗證結果(true或者false),來決定主查詢的資料結果是否保留。

那麼,這樣寫就等價於:

select * from a,先從a表做迴圈

select * from b where a.deptid = b.deptid,再從b表做迴圈.

同理,可以抽象成這樣乙個迴圈:

list<> resultset ;

for(int i=0;ifor(int j=0;jif(a[i].deptid==b[j].deptid) {

resultset.add(a[i]);

break;

資料庫最費勁的就是跟程式鏈結釋放。假設鏈結了兩次,每次做上百萬次的資料集查詢,查完就走,這樣就只做了兩次;相反建立了上百萬次鏈結,申請鏈結釋放反覆重複,這樣系統就受不了了。即mysql優化原則,就是小表驅動大表,小的資料集驅動大的資料集,從而讓效能更優。

因此,我們要選擇最外層迴圈小的,也就是,如果b的資料量小於a,適合使用in,如果b的資料量大於a,即適合選擇exist

SQL查詢中in和exists的區別

sql查詢中in和exists的區別分析 select from a where id in select id from b select from a where exists select 1 from b where a.id b.id 對於以上兩種情況,in是在記憶體裡遍歷比較,而exis...

SQL查詢中in和exists的區別分析

先上 select from a where id in select id from b select from a where exists select 1from b where a.id b.id 對於以上兩種情況,in是在記憶體裡遍歷比較,而exists需要查詢資料庫,所以當b表資料量較...

SQL查詢中in和exists的區別分析

本文出處參考 url select from a where id in select id from b select from a where exists select 1 from b where a.id b.id 對於以上兩種情況,in是在記憶體裡遍歷比較,而exists需要查詢資料庫,...