侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

mysql的索引失效

2024-05-11 星期六 / 0 评论 / 0 点赞 / 75 阅读 / 3598 字

一、成功的索引优化1.表数据如下:2.查询语句如下:explain select id, age, level from employee where dpId = 1 and age = 30 or

一、成功的索引优化

1.表数据如下:

2.查询语句如下:

explain select id, age, level from employee where dpId = 1 and age = 30 order by level

Extra: Using where; Using filesort

出现了Using filesort需要进行优化。方法很简单,为查询,分组排序的字段建索引即可。

3.建索引优化:

create index idx_employee_dla on employee(dpId, age, level)

再次查询结果如下,type为ref,使用到了索引key,Extra为Using Where; Using index,优化成功:

二、跳过左侧索引,使索引失效

索引从左往右的顺序为 id, dpId,age,level,查询时跳过左侧的索引使用>,<条件查询age索引

下面的例子中,跳过了age索引,使用了level

下面的例子中,对age使用了>,大于号。后面又使用了level索引。

Extra出现Using filesort,索引失效,需要优化。

解决办法:重新建立索引,不为age字段建立索引,其他字段建立索引即可。

drop index idx_employee_dla on employee

create index idx_employee_dla on employee(dpId, level)

三、查询索引字段中间,加入非索引字段,使索引失效

userName为非索引字段,当查询userName字段时,Extra为:Using index condition; Using filesort,需要优化。

四、使用!=,<>,is null, is not null 使索引失效

所以,一定要给所有的字段加上默认值。避免使用is not null, 这样的语句使索引失效。


五、在索引上使用or条件,使索引失效

在索引age上,使用or条件,使索引失效。


广告 广告

评论区