在工作中经常能遇到索引失效的情况,只要索引失效就导致了SQL查询慢,服务响应慢,用户体验差的情况;所以下面我们就讨论一下MySQL中索引失效的情况
口诀
全职匹配我最爱,最左前缀要遵守;
带头大哥不能死,中间兄弟不能断;
索引列上少计算,范围之后全失效;
LIKE百分写最右,覆盖索引无所谓;
不等空值还有 OR,索引影响要注意;
VAR 引号不可丢,SQL 优化有诀窍。
1.首先创建表
create table staffs(
-> id int primary key auto_increment,
-> name varchar(24) not null default '' comment '姓名',
-> age int not null default 0 comment '年龄',
-> pos varchar(20) not null default ''comment '职位',
-> add_time TIMESTAMP not null default CURRENT_TIMESTAMP comment'入职时间'
-> )charset utf8 comment '员工记录表';
2.添加测试数据
insert into staffs(name,age,pos,add_time)values ('z3',22,'manager',NOW());
insert into sta