MySQL索引失效

OR:

  查询条件包含or时,可能会导致索引失效

  只有当or左右查询字段均为索引时,才会生效

组合索引:

  组合索引,不是使用第一列索引,索引失效

  下面是一些例子,假设索引是(col1, col2, col3),那么:

  ...where col1 = 1 order by col2, col3;(√)
  ...where col1 = 1 order by col2;(√)
  ...where col1 > 1 order by col1, col2;(√)

  ...where col1 > 1 order by col2, col3;(X) // Order By必须出现索引中的第1个字段
  ...where col1 = 1 order by col2 desc, col3 asc;(X)  //Order By中三个字段的排序方向必须相同,否则会导致索引失效
  ...where col1 = 1 order by col2, col4;(X)
  ...where col1 = 1 order by col3;(X)
  ...where col1 = 1 and col2 in(1,3) order by col3;(X)


不能继续使用索引中范围条件(bettween、<、>、in等)右边的列

like 以%开头:

  使用like模糊查询,当%在前缀时,索引失效,如‘%123’

  当前缀没有%,后缀有%时,索引有效,如‘123%’

如何列类型是字符串,where时一定用引号括起来,否则索引失效:

  where a = 123 ,索引失效

  where a = ‘123’ ,索引有效

当全表扫描速度比索引速度快时,mysql会使用全表扫描,此时索引失效

在索引列上做计算,或者使用函数,索引失效

where 子句中有is null ,is not null 也无法使用索引:

  如where a is null

where 子句中使用!=,<> 也无法使用索引

猜你喜欢

转载自www.cnblogs.com/mengchunchen/p/9083046.html