-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
联合索引有一个最左前缀原则,具体是什么? #10
Comments
mysql建立多列索引(联合索引)有最左前缀的原则,即最左优先,如: 如果有一个2列的索引(col1,col2),则已经对(col1)、(col1,col2)上建立了索引; 总结: 2、比如当(张三,F)这样的数据来检索时,b+树可以用name来指定搜索方向,但下一个字段age的缺失,所以只能把名字等于张三的数据都找到,然后再匹配性别是F的数据了, 这个是非常重要的性质,即索引的最左匹配特性。(这种情况无法用到联合索引) |
测试1: 1、explain select * from tblArticle0 where applyTime=123 and auditSt =1 ; 测试结果:1和2两种情况都用到了索引key_aS_aT,所以索引顺序是可以颠倒的,只要where条件中的字段包含索引中的第一个字段即可。 |
测试2: 1、explain select * from user_test where sex = 2 测试结果:这3条sql语句都会用到联合索引sex_type_age,因为where条件中包含了第一个索引字段sex。 |
有个地方指教下 : 其他地方的资料跟你的有有点偏差,有一个3列索引(col1,col2,col3),其实是对(col1),(col1,col2),(col1,col2,col3)建立了索引,而不是你说的 : 对(col1)、(col1,col2)、(col1,col3)和(col1,col2,col3)上建立了索引; |
你好,你可以根据测试2中的示例,在测试数据库中测试下。我这边的测试结果是,只要包含联合索引中最左字段,那么在查询的时候会用到该联合索引。 |
对,从Explain种的key字段可以看到使用了联合索引.但是还是有点区别的.我根据你的示例建了一个表.
执行
执行
虽然key字段都是 |
我理解测试3 中用到的索引是(col1),并没有用到(col1,col2,col3)。 根据最左前缀原则,联合索引的顺序是(sex,type,age),测试3中查询条件只有sex 和age这两个,缺少中间的type,所以无法使用(col1,col2,col3)。 如果在测试3中想用到索引(col1,col2,col3),可以在sex 和age中间填补上一个type的全量查询。 |
问题:
联合索引有一个最左前缀原则,具体是什么?
The text was updated successfully, but these errors were encountered: