MySQL:场景索引失效场景与解决方案

小鱼儿 2022-12-14 13:49 318阅读 0赞

可能导致索引失效的场景:

  1. 索引列不独立。独立是指:列不能是表达式的一部分,也不能是函数的参数
  2. 使用了左模糊
  3. 使用OR查询的部分字段没有索引
  4. 字符串条件未使用’’引起来
  5. 不符合最左前缀原则的查询
  6. 索引字段建议添加NOT NULL约束
  7. 隐式转换导致索引失效
示例1:索引字段不独立(索引字段进行了表达式计算)
  1. explain
  2. select *
  3. from employees
  4. where emp_no + 1 = 10003;

解决方案:事先计算好表达式的值,再传过来,避免在SQLwhere条件 = 的左侧做计算

  1. explain
  2. select *
  3. from employees
  4. where emp_no = 10002;
示例2:索引字段不独立(索引字段是函数的参数)
  1. explain
  2. select *
  3. from employees
  4. where SUBSTRING(first_name, 1, 3) = 'Geo';

解决方案:预先计算好结果,再传过来,在where条件的左侧,不要使用函数;或者使用等价的SQL去实现

  1. explain
  2. select *
  3. from employees
  4. where first_name like 'Geo%';
示例3:使用了左模糊
  1. explain
  2. select *
  3. from employees
  4. where first_name like '%Geo%';

解决方案:尽量避免使用左模糊,如果避免不了,可以考虑使用搜索引擎去解决

  1. explain
  2. select *
  3. from employees
  4. where first_name like 'Geo%';
示例4:使用OR查询的部分字段没有索引
  1. explain
  2. select *
  3. from employees
  4. where first_name = 'Georgi'
  5. or last_name = 'Georgi';

解决方案:分别为first_name以及last_name字段创建索引

示例5:字符串条件未使用''引起来
  1. explain
  2. select *
  3. from dept_emp
  4. where dept_no = 3;

解决方案:规范地编写SQL

  1. explain
  2. select *
  3. from dept_emp
  4. where dept_no = '3';
示例6:不符合最左前缀原则的查询
  • 存在index(last_name, first_name)

    explain select *
    from employees
    where first_name = ‘Facello’;

解决方案:调整索引的顺序,变成index(first_name,last_name)/index(first_name)

示例7:索引字段建议添加NOT NULL约束
  • 单列索引无法储null值,复合索引无法储全为null的值
  • 查询时,采用is null条件时,不能利用到索引,只能全表扫描
  • MySQL官方建议尽量把字段定义为NOT NULL:https://dev.mysql.com/doc/refman/8.0/en/data-size.html

    explain
    select *
    from shop-dev.users
    where mobile is null;

解决方案:把索引字段设置成NOT NULL,甚至可以把所有字段都设置成NOT NULL并为字段设置默认值

示例8:隐式转换导致索引失效
  1. select emp.*, d.dept_name
  2. from employees emp
  3. left join dept_emp de
  4. on emp.emp_no = de.emp_no
  5. left join departments d
  6. on de.dept_no = d.dept_no
  7. where de.emp_no = '100001';

解决方案:在创建表的时候尽量规范一点,比如统一用int,或者bigint

发表评论

表情:
评论列表 (有 0 条评论,318人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Mysql索引失效场景

    首先我们准备一张有800万条数据的表,在没有加索引的条件下,查询全表的某一字段所耗费的时间大致在3.6S: ![在这里插入图片描述][23a74a59f6b3414e9ee

    相关 MySQL索引失效场景

    常见的导致索引失效的场景: 1、不使用索引列进行过滤:当查询中没有使用索引列作为过滤条件时,索引将无法发挥作用。例如,对于一个有索引的name列,如果查询中没有使用name作

    相关 mysql索引失效场景

    前言 之前有看过许多类似的文章内容,提到过一些sql语句的使用不当会导致MySQL的索引失效。还有一些MySQL“军规”或者规范写明了某些sql不能这么写,否则索引失效。