六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 248|回复: 0

mysql组合索引的顺序问题

[复制链接]

升级  3.33%

9

主题

9

主题

9

主题

秀才

Rank: 2

积分
55
 楼主| 发表于 2013-1-29 16:22:30 | 显示全部楼层 |阅读模式
  

【转自: http://blog.phpbean.com/a.cn/33/ 】

一张表建一个组合索引UNIQUE KEY `user_key` (`login_name`,`password`,`age`)

索引的存储顺序是按照建表时定义的顺序即login_name-》password-》age

下图是索引的存储结构



一 全键匹配


select * from table where login_name=? and password=? and age=? ;

等同

select * from table where password=?  and age=? and login_name=? ;
因为mysql会给你优化sql的顺序



二 匹配最左前缀
   
select * from table where login_name=?;只用到索引的第一列
select * from table where login_name=? and password=? 用到索引的前两个列
select * from table where login_name=?  and age=? ;只用到索引的第一列 因为跳过索引中password列了

以下语句不适用该索引

select * from table where password=?  ;
select * from table where  password=? and age=? ;
select * from table where age=? ;

三 匹配范围

select * from table where login_name like'?%'; 用到索引的第一列
select * from table where login_name=? and password like'?%' and age=? ; 用到索引的前两个列 因为引擎不能优化第一个范围条件的右边列
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表