谈谈联合索引

今日面试官问我,假设存在(a,b,c)三个字段的联合索引,问我
 1、如果where a=x and b=x,是否会用到索引?
 2、如果 where a=x and b=x order by c desc 会不会用到索引?
 3、如果 where a=x and b=x group by c  会不会用到索引?

我当时的回答是

1 否,因为没有用到c
2是,因为order by会用到索引

3 否,因为group by是在where之后,不走索引

那么我现在来检查一下我的答案。查阅了一下资料,其实建立(a,b,c)三个字段的联合索引,就是相当于建立了(a,b,c)、(a,b),a的三个索引(最佳左前缀特性),而order by是能使用最左前缀索引的,所以其实

  • where a=x and b=x ;  会用到索引(a,b)
  • where a=x and b=x order by c desc;   会用到索引(a,b,c)
  • where a=x order by b desc,c desc;    会用到索引(a,b,c)
  • order by a asc,b desc,c desc;         不会用到索引,因为排序不一致
  • order by a;使用索引a
  • where a=x order by c ;           order by没有命中索引但是where有命中索引
  • where a=x order by b,d;         where命中索引但是order by没有命中
  • where a in (x,y,m) order by b,c ;  where命中索引但是orderby没有命中,因为where使用索引的最左前缀不为常量

那么上面的1、2应该是都有用到索引的,那么3呢,group by真的没有用到索引吗?查了一下资料,得到的结论是group by和order by索引用法是一样的。所以3应该也是肯定的答案。

但是有两份资料说法有矛盾,一个说联合索引没有where的铺垫order by是不走索引的,另一个说只要遵循最左原则order by是可以走索引的,我需要验证一下后再记录。

还有联合索引的顺序也要一至才能使用索引的,就是说,where a=x order by c,b不会使用索引。那么where a=x and c=x and b=x会不会使用索引呢?这个我也需要验证一下。

以上是我今日的一些总结,
参考
https://blog.csdn.net/qq_39338079/article/details/97381667 
https://blog.csdn.net/q6627666/article/details/89607932
https://www.jianshu.com/p/f65be52d5e2b

猜你喜欢

转载自www.cnblogs.com/smallzhen/p/12702491.html