上篇介紹了MySql什麼時候會嘗試使用索引,本文介紹一下我瞭解的不會使用索引的情況, 仍然使用上次建立好的表
1. where 子句中like 使用了字首萬用字元 %keyword
select * from test_user where name like "%Kiven%";
複製程式碼

2. 使用>, >=, <,<=, !=,NOT IN 範圍查詢或否定查詢,且範圍查詢時選擇的邊界查詢條件範圍過大
select * from test_user where height>=180
# 不會使用索引
複製程式碼

select * from test_user where height>=190
# 會使用索引
複製程式碼

3. 資料型別隱式轉換
例如:name欄位為varchar型別的
select * from test_user where name=1
複製程式碼
將不能使用索引,而
select * from test_user where name='1'
複製程式碼
可以使用索引


原因是當不同的欄位型別比較時,MySql會做引式型別轉換,而 int型別的1可能等於 '01', '0001'或者 '01.e1'
4. 不符合最左匹配原則(聯合索引)
我們建立的索引順序是
KEY `idx_name_height_weight` (`name`,`height`,`weight`)
複製程式碼
所以使用的時候where子句也不能跳過前一個聯合索引列
# 比如直接聯合索引的最後一列是不支援的
select * from test_user where weight=65
複製程式碼

# 而使用全部索引列做查詢條件是可以的
select * from test_user where weight=65 AND name='Tom' AND `height`=160
複製程式碼

6. 在索引列上進行運算
select * from test_user where `height`+10=160
#是不會使用索引的,可以寫成
select * from test_user where `height`=160-10
# 就能夠使用索引了
複製程式碼
在索引使用方面MySql本身幫我們做了很多優化,有時候不一定會按照我們的想法去使用索引,接下來還需要探索