九个实验:MySQL 联合索引的最左匹配原则

2023年 10月 1日 71.8k 0

theme: smartblue
highlight: vs2015

你好,我是悟空。

本篇主要通过几次实验来看看 MySQL 联合索引的最左匹配原则。

环境:MySQL 版本:8.0.27

执行计划基础知识

possible_keys:可能用到的索引

key:实际用到的索引

type:

  • ref:当通过普通的二级索引列与常量进行等值匹配的方式 询某个表时
  • const:当我们根据主键或者唯一得二级索引列与常数进行等值匹配时,对单表的访问方法就是 const
  • range:如果使用索引获取某些单点扫描区间的记录。
  • index:当可以使用覆盖 ,但需要扫描全部的索引记录时。
  • Extra:

  • Using index 索引覆盖
  • Using Where 当某个搜索条件需要在 server 层进行判断时
  • Using index for skip scan 跳跃扫描
  • Using index condtion 索引下推
  • 最左匹配原则

    最左优先,以最左边的为起点任何连续的索引都能匹配上。同时遇到范围查询(>、1 and b=2,a 字段可以匹配上索引,但 b 值不可以,因为a的值是一个范围,在这个范围中b是无序的。

    实验数据

    数据表: user_behavior

    字段:a,b,c,d

    联合索引:abc

    实验一

    条件 abc,查询列 abc

    MySQL 语句

    EXPLAIN
    select a,b,c from user_behavior where a = '1000040' and b = '1082963' and c = '1575622'
    

    实验结果

    实验结论

    是否使用到了联合索引:✅

    索引覆盖(Extra: Using index)

    实验二

    查询条件

    条件 abc,查询列 abc,

    MySQL 语句

    EXPLAIN select * from user_behavior where a = '1000040' and b = '1082963' and c = '1575622'
    

    实验结果

    实验结论

    是否使用到了联合索引:✅

    三、条件 bc,查询列 abcd

    查询条件

    EXPLAIN
    select *
    from user_behavior where b =
    '1082963' and c = '1575622'
    

    实验结果

    实验结论

    是否使用到了联合索引:❌

    四、条件 bc,查询列 bc

    查询条件

    EXPLAIN
    select b, c from user_behavior where b = '1082963' and c = '1575622' 
    

    实验结果

    实验结论

    使用联合索引 ✅,Using index for skip scan

    五、条件 bc,查询列 abc

    查询条件

    EXPLAIN select a, b,
    c from user_behavior where b = '1082963' and c =
    '1575622'
    

    实验结果

    实验结论

    使用联合索引 ✅,Using index for skip scan

    六、条件 ca,查询列 ca

    EXPLAIN select c,a from user_behavior where a = '1000040' and c = '1575622'
    

    实验结果

    实验结论

    使用联合索引 ✅,只能用到 a

    七、条件 bca,查询列abcd

    查询条件

    EXPLAIN select * from user_behavior where b = '1082963' and c = '1575622' AND a = '1000040'
    

    实验结果

    实验结论

    使用联合索引 ✅

    八、条件 bac,查询列abcd

    查询条件

    ​
    EXPLAIN select * from user_behavior where b = '1082963' AND a = '1000040'and c = '1575622'
    

    实验结果

    实验结论

    使用联合索引 ✅

    九、条件 ac,查询列 abcd

    查询条件

    EXPLAIN
    ​
    select * from user_behavior where a = '1082963' and
    ​
    c = '1575622'
    

    实验结果

    实验结论

    使用联合索引✅,用到 a,索引下推

    相关文章

    JavaScript2024新功能:Object.groupBy、正则表达式v标志
    PHP trim 函数对多字节字符的使用和限制
    新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
    使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
    为React 19做准备:WordPress 6.6用户指南
    如何删除WordPress中的所有评论

    发布评论