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; //索引查询