浅谈Mysql索引的最左匹配原则

Royal
2021-08-21 / 0 评论 / 338 阅读 / 正在检测是否收录...

最左匹配原则

最左匹配原则就是指在联合索引中,如果你的 SQL 语句中用到了联合索引中的最左边的索引,那么这条 SQL 语句就可以利用这个联合索引去进行匹配.
例如某user表现有索引(name_age_email)

CREATE INDEX name_age_email ON user  (`name`,`age`,`email`)

kslm0228.png
kslm21z0.png
现在测试如下sql语句:

  1. explain select * from user where name='tom' and age=21 and email ='test@email.com'; 

    kslm6nvs.png
    结果:这样可以利用到定义的联合索引(name_age_email),用上name,age,email

  2. explain select * from user where name='tom' and age=21; 

    kslm9p3z.png
    结果:这样可以利用到定义的联合索引(name_age_email),用上name,age

  3. explain select * from user where age=21 and name='tom'; 

    kslmbw1u.png
    结果:这样可以利用到定义的联合索引(name_age_email),用上name,age(mysql有查询优化器)

  4. explain select * from user where name='tom'; 

    kslmedgm.png
    结果:这样可以利用到定义的联合索引(name_age_email),用上name

  5. explain select * from user where  age=21 and email ='test@email.com'; 

    kslmfs91.png
    结果: 这样不可以利用到定义的联合索引(name_age_email)

  6. explain select * from user where name='tom' and email ='test@email.com'; 

    kslmicf0.png
    结果:这样可以利用到定义的联合索引(name_age_email),用上name索引,但是age和email索引用不到


也就是说通过最左匹配原则你可以定义一个联合索引,但是使得多中查询条件都可以用到该索引,避免了重复建索引造成的资源浪费,索引不是建的越多越好!
下面几种情况时索引也会停止匹配:

  1. 当遇到范围查询(>、<、between、like)就会停止匹配。也就是:

    select * from user where name='tom' and age>20 and email ='test@email.com'; #这样name,age可以用到(name_age_email),email索引用不到 

    这条语句只有name,age 会用到索引,email都不能用到索引。这个原因可以从联合索引的结构来解释。
    2.但是如果是建立(name,email,age)联合索引,则name,age,email都可以使用索引,因为优化器会自动改写为最优查询语句

    CREATE INDEX name_age_email ON user  (`name`,`email`,`age`)

    kslmshxh.png

    explain select * from user where name='tom' and age>20 and email ='test@email.com'; 

    kslmtvjx.png
    结果:如果是建立(name,email,age)联合索引,则a,b,c都可以使用索引

    优化器改写为

    select * from user where name='tom' and email ='test@email.com' and age>20;

通过以上sql分析:索引index1:(a,b,c),只会走a、a,b、a,b,c 三种类型的查询,其实这里说的有一点问题,a,c也走,但是只走a字段索引,不会走c字段,c肯定是无序了,所以c就没法走索引,数据库会觉得还不如全表扫描c字段来的快。
以index (a,b,c)为例建立这样的索引相当于建立了索引a、ab、abc三个索引。一个索引顶三个索引当然是好事,毕竟每多一个索引,都会增加写操作的开销和磁盘空间的开销。

0

评论

博主关闭了当前页面的评论