您好,登錄后才能下訂單哦!
小編給大家分享一下mysql索引失效的原因,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
索引對(duì)于MySQL而言,是非常重要的篇章。索引知識(shí)點(diǎn)也巨多,要想掌握透徹,需要逐個(gè)知識(shí)點(diǎn)一一擊破,今天來先來聊聊哪些情況下會(huì)導(dǎo)致索引失效。
圖片總結(jié)版
相關(guān)免費(fèi)學(xué)習(xí)推薦:mysql視頻教程
explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';
和索引順序無關(guān),MySQL底層的優(yōu)化器會(huì)進(jìn)行優(yōu)化,調(diào)整索引的順序 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';
如計(jì)算、函數(shù)、(自動(dòng)or手動(dòng))類型轉(zhuǎn)換等操作,會(huì)導(dǎo)致索引失效從而全表掃描 explain select * from user where left(name,5) = 'zhangsan' and age = 20 and phone = '18730658760';
索引范圍條件右邊的索引列會(huì)失效 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在使用不等于(!=、<>)的時(shí)候無法使用索引會(huì)導(dǎo)致全表掃描(除覆蓋索引外) explain select * from user where age != 20; explain select * from user where age <> 20;
索引失效 explain select * from user where name like '%zhangsan';
索引生效 explain select * from user where name like 'zhangsan%';
explain select * from user where name = 2000;
少用or explain select * from user where name = '2000' or age = 20 or pos ='cxy';
正常(索引參與了排序) explain select * from user where name = 'zhangsan' and age = 20 order by age,pos; 備注:索引有兩個(gè)作用:排序和查找
導(dǎo)致額外的文件排序(會(huì)降低性能) 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;//含非索引字段
正常(索引參與了排序) explain select name,age from user where name = 'zhangsan' group by age; 備注:分組之前必排序(排序同order by)
導(dǎo)致產(chǎn)生臨時(shí)表(會(huì)降低性能) 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
看完了這篇文章,相信你對(duì)mysql索引失效的原因有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。