Mysql 联合索引,最左前缀原则、失效问题

1、为什么索引支持最左索引前缀原则?
针对数据库存储引擎为InnoDB来说,索引的底层数据结构是B+树,当设置联合索引时,只能按一个键值构造B+树,因此索引只支持最左索引前缀原则。

2、使用联合索引时需注意设置的索引是否被正确使用上,举例说明,现在针对字段a、b、c建立联合索引:

  • 全值匹配时,用到了索引,where子句几个搜索条件顺序调换时也会用到索引,因为Mysql中有查询优化器,会自动优化查询顺序
    select * from table_name where a ='' and b='' and c=''; //走索引查询
    select * from table_name where  b='' and a ='' and c=''; //搜索条件顺序调换,不影响索引查询
    
  • 部分值匹配时,只要条件中有最左索引项就会用到索引
    select * from table_name where a ='' and b=''; //走索引查询
    select * from table_name where a ='' and c=''; //走索引查询
    
  • 条件中没有最左索引,不会用到索引,全表扫描
    select * from table_name where b='' and c=''; //全表扫描
    
  • 匹配范围值,可以对最左边的列进行范围查询,范围查询指,<、>、between等
    select * from table_name where a<'' and c=''; //索引查询
    select * from table_name where a between '' and ''; //索引查询
    
    select * from table_name where a like 'A%'; //走索引查询
    select * from table_name where  a like '%A'//全表查询
    select * from table_name where  a like '%A%'//全表查询
    
  • 精确匹配最左列 and 范围匹配另外一列 ,会使用索引
    select * from table_name where a='' and c>''; //索引查询
    
  • order排序
    select * from table_name order by a,b,c; //索引查询
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容