今天遇到的問題查詢需要使用 where in ,雖然MySQL對於IN做了相應的優化,即將IN中的常量全部存儲在一個數組里面,而且這個數組是排好序的。但是如果數值較多,產生的消耗也是比較大的。
1:select id from t where num in(1,2,3) 對於連續的數值,能用between就不要用in了;
2:使用join連接來替換。
下面兩段是我查資料時在評論區看到的,實際操作確實優化作用很大,特此記錄:
優化前:
select docId from tab1 where word in (select word from tab1 where docId=123) group by docId limit 1000;
優化后: select docId from (select word from tab1 where docId=123) as t2 join tab1 t on t.word=t2.word where t2.word is not null GROUP BY docId limit 1000