mysql索引最左匹配原则

联合索引的b+结构

image.png

联合索引

create table test(
a int ,
b int,
c int,
d int,
key index_abc(a,b,c)
)engine=InnoDB default charset=utf8;

只要where有a的查询就会用到上面的联合索引,无关顺序
比如:
explain select * from test where a<10 ;
explain select * from test where b<10 and a <10;
explain select * from test where b<10 and a <10 and c<10;
explain select * from test where a<10 and c <10;(a走索引了,c没走)
explain select * from test where a<10 and b <10;
explain select * from test where a<10 and b <10 and c<10;

下面不会用到联合索引(没有用到a)
explain select * from test where b<10 and c <10;

为什么?

当b+树的数据项是复合的数据结构,比如(name,age,sex)的时候,b+数是按照从左到右的顺序来建立搜索树的,比如当(张三,20,F)这样的数据来检索的时候,b+树会优先比较name来确定下一步的所搜方向,如果name相同再依次比较age和sex,最后得到检索的数据;

但当(20,F)这样的没有name的数据来的时候,b+树就不知道下一步该查哪个节点,因为建立搜索树的时候name就是第一个比较因子,必须要先根据name来搜索才能知道下一步去哪里查询。

比如当(张三,F)这样的数据来检索时,b+树可以用name来指定搜索方向,但下一个字段age的缺失,所以只能把名字等于张三的数据都找到,然后再匹配性别是F的数据了, 这个是非常重要的性质,即索引的最左匹配特性。

单个索引

create table test(
a int ,
b int,
key index_a(a),
key index_b(b),
)engine=InnoDB default charset=utf8;

explain select * from test where a<10 and b <10;
explain select * from test where b <10 and a<10;

实际上只会用到index_a索引

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容