索引並不是不會失效,有時就算是where查詢字段中添加了索引,索引也會失效,失效場景如下:
1.查詢條件包含or
當or左右查詢字段只有一個是索引,該索引失效,explain執行計劃key=null;只有當or左右查詢字段均爲索引時,纔會生效;
2.組合索引,不是使用第一列索引,索引失效
如果select * from key1=1 and key2= 2;建立組合索引(key1,key2);
select * from key1 = 1;組合索引有效;
select * from key1 = 1 and key2= 2;組合索引有效;
select * from key2 = 2;組合索引失效;不符合最左前綴原則
3.like 以%開頭
使用like模糊查詢,當%在前綴時,索引失效;
eg: select * from aaa t where t.a1 like '%123' ;
當前綴沒有%,後綴有%時,索引有效;
eg: select * from aaa t where t.a1 like '123%' ;
4.如何列類型是字符串,where時一定用引號括起來,否則索引失效不用引號括起來
eg:
失效: select * from aaa t where t.a1 = 123';
不失效: select * from aaa t where t.a1 = '123';