MySQL 索引失效的几种类型以及解决方式

索引失效的情况有哪些?

  1. 索引列不独立

  2. 使用了左模糊

  3. 使用 or 查询部分字段没有使用索引

  4. 字符串条件没有使用 ''

  5. 不符合最左前缀原则的查询

  6. 索引字段没有添加 not null 约束

  7. 隐式转换导致索引失效

索引列不独立是指被索引的这列不能是表达式的一部分,不能是函数的参数,比如下面的这种情况

select id,name,age,salary from table_name where salary + 1000 = 6000;

salary 列被用户表达式的计算了,这种情况下索引就会失效,解决方式就是提前计算好条件值,不要让索引列参与表达式计算。

索引字段作为函数的参数

select id,name,age,salary from table_name where substring(name,1,3)= 'luc';

解决方式是什么呢,可以提前计算好条件,不要使用索引,或者可以使用其他的 sql 替换上面的,比如,上面的sql 可以使用 like 来代替

select id,name,age,salary from table_name where name like 'luc%';

使用了左模糊

select id,name,age,salary from table_name where name like '%lucs%';

平时尽可能避免用到左模糊,可以这样写

select id,name,age,salary from table_name where name like 'lucs%';

如果实在避免不了左模糊查询的话,考虑一下搜索引擎 比如 ES

or 查询部分字段没有使用索引

select id,name,age,salary from table_name where name ='lucs' and age >25

这种情况,可以为 name 和 age 都建立索引,否则会走全表扫描。

字符串条件没有使用 ''

  • 上面的这条 sql phone 字段类型是 字符串类型的,但是没有使用 '13088772233 ', SQL 就全表扫描了,所以字符串索引要使用 ‘’
select id,name,age,salary from table_name where phone='13088772233 '

不符合最左前缀原则的查询

例如有这样一个组合索引 index(a,b,c)

select * from table_name where b='1'and c='2'select * from table_name where c='2'
// 上面这两条 SQL 都是无法走索引执行的

最左原则,就是要最左边的优先存在,我不在的话,你们自己就玩不动了,除非你自己单独创立一个索引,下面这几条 SQL 就可以走索引执行

select * from table_name where a = 'asaa' and b='1'and c='2'select * from table_name where a = 'asda' and b='1231' // 上面这两条是走索引的,但是下面这条你觉得索引应该怎么走,是全部走,还是部分走索引?select * from table_name where a = 'asda' and c='dsfsdafsfsd'

索引字段没有添加 not null 约束

select * from table_name where a is null;// 这条sql就无法走索引执行了,is null 条件 不能使用索引,只能全表扫描了// mysql 官方建议是把字段设置为 not null

所以针对这个情况,在mysql 创建表字段的时候,可以将需要索引的字符串设置为 not null default '' 默认空字符串即可

隐式转换

关联表的两个字段类型不一致会发生隐式转换

select * from table_name t1 left join table_name2 t2 on t1.id=t2.tid;// 上面这条语句里,如果 t1 表的id 类型和 t2 表的tid 类型不一致的时候,就无法// 按索引执行了。// 解决方式就是统一设置字段类型。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧木易

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值