13. 知道什么是左前缀原则嘛 ?
在mysql建立联合索引时会遵循左前缀匹配的原则,即最左优先,在检索数据时从联合索引的最左边开始匹配,组合索引的第一个字段必须出现在查询组句中,这个索引才会被用到 ;
例如 : create index index_age_name_sex on tb_user(age,name,sex);
上述SQL语句对 age
,name
和sex
建一个组合索引index_age_name_sex
,实际上这条语句相当于建立了(age) , (age,name) , (age,name,sex)
三个索引 .
select * from tb_user where age = 49 ; -- 使用索引 select * from tb_user where age = 49 and name = 'Alice' ; -- 使用索引 select * from tb_user where age = 49 and name = 'Alice' and sex = 'man'; -- 使用索引 select * from tb_user where age = 49 and sex = 'man'; -- 使用索引 , 但是只有 age 匹配索引 sex没有走索引 select * from tb_user where name = 'Alice' and age = 49 and sex = 'man' ; -- 使用索引 , 因为MySQL的查询优化器会自动调整 where 子句的条件顺序以使用适合的索引 select * from tb_user where name = 'Alice' and sex = 'man' ; -- 不会使用索引