MySql中in和exists效率

2021-09-07 07:38:18 字數 907 閱讀 6705

詳見:

mysql中的in語句是把外表和內錶作hash 連線,而exists語句是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。一直大家都認為exists比in語句的效率要高,這種說法其實是不準確的。這個是要區分環境的。

如果查詢的兩個表大小相當,那麼用in和exists差別不大。 

如果兩個表中乙個較小,乙個是大表,則子查詢表大的用exists,子查詢錶小的用in: 

例如:表a(小表),表b(大表)

1:select * from a where cc in (select cc from b) 效率低,用到了a表上cc列的索引;

select * from a where exists(select cc from b where cc=a.cc) 效率高,用到了b表上cc列的索引。 

相反的2:

select * from b where cc in (select cc from a) 效率高,用到了b表上cc列的索引;

select * from b where exists(select cc from a where cc=b.cc) 效率低,用到了a表上cc列的索引。

not in 和not exists如果查詢語句使用了not in 那麼內外表都進行全表掃瞄,沒有用到索引;而not extsts 的子查詢依然能用到表上的索引。所以無論那個表大,用not exists都比not in要快。 

in 與 =的區別 

select name from student where name in ('zhang','wang','li','zhao'); 

與 select name from student where name='zhang' or name='li' or name='wang' or name='zhao' 

的結果是相同的。

MySQL中的in和exists區別

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需要查詢資...

MySQL中 in和exists的區別

a表 100條資料 b 10條資料 select from a where id in select aid from b 先執行括號裡面的查詢,然後執行外面,總共需要查詢的次數的 b 1 11次 需要注意的是 括號裡面的查詢會快取到記憶體中 select from a where exists s...

MySQL中IN和EXISTS的用法

exists對外表用loop逐條查詢,每次查詢都會檢視exists的條件語句,當 exists裡的條件語句能夠返回記錄行時 無論記錄行是的多少,只要能返回 條件就為真,返回當前loop到的這條記錄,反之如果exists裡的條 件語句不能返回記錄行,則當前loop到的這條記錄被丟棄,exists的條件...