最近面试时遇到一个索引的“基础”问题,平时看的多,眼花缭乱的,到最后面试时什么都记不住,也什么都记一点。
题目:
index idx_abc(a,b,c)
primary key(id)
select * from myTest where a=3 and b>7 and c>3;
问sql是否走索引?
explain 这条sql,extra栏应该是using index condition(mysql5.6后),这个查询是走索引的,可以用到a, b>7、c>3的条件会在使用idx_abc定位a=3后,在存储引擎层继续判断当前索引是否满足b>7 and c>3,满足则将这条索引记录对应的主键返回server层,回表查询 myTest中其他非索引字段(假设myTest还有字段‘d’,‘e’)。
如果sql改成
select id,a,b,c from myTest where a=3 and b>7 and c>3;
则explain的结果则应当是:using where;using index。
这里的查询列在覆盖索引“idx_abc”范围内,不需要回表查其他字段,只是这里的using where 是在索引中过滤。
参考链接:
https://www.cnblogs.com/wy123/p/7366486.html
https://www.jianshu.com/p/9927a2307329
https://www.cnblogs.com/my_life/articles/10221132.html
前人总结的非常好,时常看下。