Mysql索引失效案例分析

新建表staffs的索引为:idx_nameAgePos;
1、尽量使用全值匹配:即索引包含哪些字段,就使用哪些字段查询;

select * from staffs where name = 'July' and age = 23 and pos =  'dev';

在这里插入图片描述

2、最佳左前缀法则:查询从索引的最左前列开始,且不跳过索引中的列:

// 部分匹配
select * from staffs where name = 'July';

在这里插入图片描述

// 部分匹配
select * from staffs where name = 'July' and pos = 'dev';

在这里插入图片描述

// 索引失效
select * from staffs where pos = 'dev';
// 索引失效
select * from staffs where age = 23 and pos = 'dev';

3、不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描;

// 索引匹配
explain select * from staffs where name = 'July';

在这里插入图片描述

// 索引失效(left为截取字符串函数,mysql自带函数,类似于java的subString)
explain select * from staffs where left(name, 4) = 'July';

4、存储引擎不能使用索引中范围条件右边的列;

explain select * from staffs where name = 'July' and age = 25 and pos = 'manager';

在这里插入图片描述

explain select * from staffs where name = 'July' and age > 25 and pos = 'manager';

在这里插入图片描述
5、尽量使用覆盖索引(只访问索引的查询(索引列和查询列一致)),减少select *;
在这里插入图片描述
6、在使用不等于(!=或<>)的时候无法使用索引会导致全表扫描;
7、is null、is not null也无法使用索引;
新建表user的索引为:idx_user_nameAge;
8、like以通配符开头(‘%abc…’),mysql索引失效会变成全表扫描操作;

explain select * from user where name like '%aa%';

在这里插入图片描述

explain select * from user where name like 'aa%';

在这里插入图片描述

explain select name,age,email from user where name like '%aa%';

在这里插入图片描述
Q:如何解决like’%字符串%'时索引不被使用?
A:使用索引全覆盖(索引字段与查询字段一致)。
9、字符串不加单引号会导致索引失效(涉及隐性转换);

explain select * from user where name = '2000';

在这里插入图片描述

explain select * from user where name = 2000;

在这里插入图片描述
10、少用or,用它连接时会导致索引失效。

explain select * from user where name = '2000' or name = '1aa1';

在这里插入图片描述
总结:
假设index(a,b,c)

where语句索引是否被使用
where a = 3是(使用到a)
where a = 3 and b = 5是(使用到a,b,但c未被使用)
where a = 3 and a = 5 and c = 4是(使用到a,b,c)
where b = 3 或者 where b = 3 and c = 4 或者 where c = 4
where a = 3 and c = 5是(使用到a,缺少b,c未被使用)
where a = 3 and b > 5 and c = 5是(使用到a,b, c在范围之后,未被使用)
where a = 3 and b like ‘kk%’ and c = 4是(使用到a,b,c在范围之后,未被使用)

优化总结口诀
全值匹配我最爱,最左前缀要遵守;
带头大哥不能死,中间兄弟不能断;
索引列上少计算,范围之后全失效;
like百分写最右,覆盖索引不写星;
不等控制还有or,索引失效要少用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值