sql語句in和exists的效率

2021-07-11 12:36:01 字數 512 閱讀 2698

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

和select a.* from a where a.id in (select b.id from b)

的效率比較

1.如果子查詢得出的結果集記錄較少,主查詢中的表較大且又有索引時應該用in;

2.如果外層的朱查詢記錄較少,子查詢中的表大又有索引時使用exists;

其實我們區分in和exists主要是造成了驅動順序的改變(這是效能變化的關鍵),

如果是exists,那麼以外層表為驅動表,先被訪問,如果是in,那麼先執行子查詢,所以我們會以驅動表的快速返回為目標,那麼就會考慮到索引及結果集的關係了 ,

另外in時不對null進行處理。

3.另外select a. * from a where a.id = 1 and a.id = 2 and a.id = 3比起in和exists效率低並且難看

sql語句中的exists和in

比如在northwind資料庫中有乙個查詢為 select c.customerid,companyname from customers c where exists select orderid from orders o where o.customerid c.customerid 這裡面的...

SQL語句中IN和EXISTS的效率問題

in select from a where id in select id from b 此處select id from b只會執行一次,將所有資料快取到記憶體,然後遍歷a表中的每條資料進行判斷是否存在。exist select from a as a where exists select i...

sql語句中exists和in的區別和應用

表展示 首先,查詢中涉及到的兩個表,乙個user和乙個 order 表,具體表的內容如下 user表 order表 確定給定的值是否與子查詢或列表中的值相匹配。in在查詢的時候,首先查詢子查詢的表,然後將內錶和外表做乙個笛卡爾積,然後按照條件進行篩選。所以相對內錶比較小的時候,in的速度較快。具體s...