索引對於MySQL而言,是很是重要的篇章。索引知識點也巨多,要想掌握透徹,須要逐個知識點一一擊破,今天來先來聊聊哪些狀況下會致使索引失效。
圖片總結版
全值匹配(索引最佳)
explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';
和索引順序無關,MySQL底層的優化器會進行優化,調整索引的順序
explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';
一、違反最左前綴法則
若是索引有多列,要遵照最左前綴法則
即查詢從索引的最左前列開始而且不跳過索引中的列
explain select * from user where age = 20 and phone = '18730658760' and pos = 'cxy';
二、在索引列上作任何操做
如計算、函數、(自動or手動)類型轉換等操做,會致使索引失效從而全表掃描
explain select * from user where left(name,5) = 'zhangsan' and age = 20 and phone = '18730658760';
三、索引範圍條件右邊的列
索引範圍條件右邊的索引列會失效
explain select * from user where name = 'zhangsan' and age > 20 and pos = 'cxy';
四、儘可能使用覆蓋索引
只訪問索引查詢(索引列和查詢列一致),減小select*
explain select name,age,pos,phone from user where age = 20;
五、使用不等於(!=、<>)
mysql在使用不等於(!=、<>)的時候沒法使用索引會致使全表掃描(除覆蓋索引外)
explain select * from user where age != 20;
explain select * from user where age <> 20;
六、like以通配符開頭('%abc')
索引失效
explain select * from user where name like '%zhangsan';
索引生效
explain select * from user where name like 'zhangsan%';
七、字符串不加單引號索引失效
explain select * from user where name = 2000;
八、or鏈接
少用or
explain select * from user where name = '2000' or age = 20 or pos ='cxy';
九、order by
正常(索引參與了排序)
explain select * from user where name = 'zhangsan' and age = 20 order by age,pos;
備註:索引有兩個做用:排序和查找
致使額外的文件排序(會下降性能)
explain select name,age from user where name = 'zhangsan' order by pos;//違反最左前綴法則
explain select name,age from user where name = 'zhangsan' order by pos,age;//違反最左前綴法則
explain select * from user where name = 'zhangsan' and age = 20 order by created_time,age;//含非索引字段
十、group by
正常(索引參與了排序)
explain select name,age from user where name = 'zhangsan' group by age;
備註:分組以前必排序(排序同order by)
致使產生臨時表(會下降性能)
explain select name,pos from user where name = 'zhangsan' group by pos;//違反最左前綴法則
explain select name,age from user where name = 'zhangsan' group by pos,age;//違反最左前綴法則
explain select name,age from user where name = 'zhangsan' group by age,created_time;//含非索引字段
使用的示例數據
mysql> show create table user \G
******************************************************
Table: user
Create Table: CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(10) DEFAULT '0',
`pos` varchar(30) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name_age_pos_phone` (`name`,`age`,`pos`,`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci