mysql索引最优左前缀

mysql 在使用联合索引时会有一个最优左前缀的一个原则

其实就是 where条件后跟随的多个条件字段使用复合索引的一个规则(引用别人的一句话:带头大哥不能死,中间兄弟不能断)

比如 user表  字段 id  name age  salary    创建复合索引 (name age  salary )  

当创建(a,b,c)复合索引时,相当于创建了(a)单列索引,(a,b)组合索引以及(a,b,c)组合索引

想要索引生效的话,只能使用 a和a,b和a,b,c三种组合

1.有带头大哥

select * from user where name='qiaofeng' and age= 28 and salary = 11000

此时是走索引的

 

2.有带头大哥,有中间兄弟

select * from user where name='qiaofeng' and age= 28 

此时是走索引的

 

3.有带头大哥,没有中间兄弟

select * from user where name='qiaofeng' and and salary = 11000

此时只有name字段走索引的, 而salary不走索引

 

4.没有带头大哥

select * from user where  age= 28 and and salary = 11000

此时是没有匹配索引的

 

另外,where后条件字段顺序不按照索引顺序 也是没问题的,因为mysql 在查询时会自动根据字段的最大化的匹配索引

select * from user where age= 28 and name='qiaofeng'  也是走索引的

 

posted @ 2021-01-13 14:09  问道有先后  阅读(90)  评论(0)    收藏  举报