优秀的编程知识分享平台

网站首页 > 技术文章 正文

MySQL中使用索引中范围条件右边的列,导致索引失效案例分析

nanyue 2024-10-28 16:38:07 技术文章 16 ℃

前提

创建user表联合索引name、age、pos

mysql> create index user_nameAgePos on user(name,age,pos);


案例分析

  1. 使用name查看执行结果
mysql> explain select * from user where name="marry";


结果:使用到了索引(type=ref,ken_len=768,ref=const)


  1. 使用name、age查看执行结果
mysql> explain select * from user where name="marry" and age=34;

结果:使用到了索引(type=ref,ken_len=773,ref=const,const),通过ken_lenth的长度和ref的变化我们就可以看出索引使用了name,并且使用了age


  1. 全值匹配查看执行结果
mysql> explain select * from user where name="marry" and age=34 and pos="dev";

结果:使用到了索引(type=ref,ken_len=1541,ref=const,const,const),通过ken_lenth的长度和ref=(const,const,const)的变化我们就可以看出索引使用了name、age、pos


  1. 如果使用全值匹配,且age取范围值的时候我们来查看执行结果
mysql> explain select * from user where name="marry" and age>14 and pos="dev";

结果:使用到了索引,但type=range,ken_lenth=773,ref=NULL,通过执行结果分析我们就可以得知索引失效了,只是部分使用到索引(name和age)。


案例对比分析:

  1. 通过案例1、2、3、4我们可以通过type、ref、ken_lenth来判读我们创建的索引是否失效,且很明显在案例4中由于使用了索引范围条件右边的列导致索引失效。
  2. 由案例4的key_lenth=773和案例1中的ken_lenth=773,实际上整个语句中只用到了name和age索引,但这里的age仅仅只是拿来排序,pos索引就没有使用到。


结论

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


点击关注发私信或评论交流文章中有问题的地方,相互学习和答疑

最近发表
标签列表