Mysql索引优化整理
2018-07-11 本文已影响60人
_Mitch
索引优化总结口诀:
全值匹配我最爱,最左前缀要遵守;
带头大哥不能死,中间兄弟不能断;
索引列上少计算,范围之后全失效;
like百分写最右,覆盖索引不写*;
不等控制还有or,索引失效要少用;
var引号不能丢,sql高级也不难;
新建一张表:
![](https://img.haomeiwen.com/i5901013/911a063f7daffc58.png)
创建索引
create index idx_name_age on student(name,age);
查看索引
show index from student;
![](https://img.haomeiwen.com/i5901013/d5fb8af8fef07798.png)
接下来我们使用explain来测试
全值匹配我最爱
explain select * from student where name = '张三' and age = 1;
![](https://img.haomeiwen.com/i5901013/e6b7d80c3e4b6e7b.png)
最左前缀要遵守,带头大哥不能死,中间兄弟不能断
explain select * from student where age = 1;
![](https://img.haomeiwen.com/i5901013/37ae5ab47cef169d.png)
索引列上少计算
explain select * from student where left(name,1) = '张' and age = 1;
![](https://img.haomeiwen.com/i5901013/ddaad9e86bbf8566.png)
范围之后全失效
explain select * from student where age > 1 and name = '王五';
![](https://img.haomeiwen.com/i5901013/32100e56561738a5.png)
like百分写最右
explain select * from student where name like '%张';
![](https://img.haomeiwen.com/i5901013/fccc7c573c8f21cc.png)
可以加上覆盖索引解决
覆盖索引不写*
explain select * from student where name = 'zhangsan';
![](https://img.haomeiwen.com/i5901013/d8d56b7dd552c02b.png)
不等控制还有or,索引失效要少用
explain select * from student where name = '张三' or age = 2;
![](https://img.haomeiwen.com/i5901013/7c2eb244547ab2b8.png)
explain select * from student where name != '张三';
![](https://img.haomeiwen.com/i5901013/4fda585c542c95c3.png)