mysql 存在索引但不能使用索引的典型場景


mysql 演示數據庫:http://downloads.mysql.com/docs/sakila-db.zip

以%開頭的LIKE查詢不能夠利用B-tree索引


 

explain select * from actor where last_name like '%NI%'\G;

 

 

explain select * from actor where last_name like 'NI%'\G;

 

解決辦法 

先掃描索引 last_name獲取滿足條件的%NI%的主鍵actor_id列表,之后根據主鍵回表去檢索記錄,這樣訪問避開了全表掃描actor表產生的大量IO請求。

explain select * from (select actor_id from actor where last_name like '%NI%') a,actor b where a.actor_id = b.actor_id\G;

 

 

 

數據類型出現隱式轉換


 

 

 explain select * from actor where last_name=1\G;

 

 

 explain select * from actor where last_name='1'\G; 

 

 

 

復合索引的情況下,查詢條件不滿足索引最左的原則


 

 

 explain select * from payment where amount=3.98 and last_update='2016-02-15 22:12:32'\G;

 

 

 

Mysql估計使用索引比全表掃描慢


 

 

update film_text set title =concat('S',title);

explain select * from film_text where title like 'S%'\G;

 

 

可以看出全表掃描需要訪問的記錄rows為1000,代價cost計算為233.53;

通過idx_title_desc_part索引掃描訪問記錄rows為998,代價cost為1198.6  要高於全表掃描的時間,mysql會選擇全表掃描

 

 

 

用or分割開的條件,or前條件有索引,or后的列沒有索引


 

 

用or分割開的條件,or前條件有索引,or后的列沒有索引,那么涉及的索引不會被用到

 因為or后面的條件沒有索引,那么后面的查詢肯定要進行全表掃描,在存在全表掃描的情況下,就沒有必要多一次索引掃描增加IO訪問。

explain select * from payment where customer_id =203 or amount=3.96\G;

 

 

負向查詢(not  , not in, not like, <>, != ,!>,!<  ) 不會使用索引


 

 

 

 

 

獨立的列 索引 不能是表達式的一部分


 

 

select * from  xxxx where id+1;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM