表格创建如下:
1.创建联合索引
ALTER table user add INDEX p_n_u(pid,name,user_no)
2.索引对应的key_len如下:
pid int(11) unsigned key_len=4
name char(32) key_len=32*3=96
user_no char(11) key_len=11*3=33
注释:索引的key_len对应计算如下:
char和varchar类型key_len计算公式: varchr(N)变长字段且允许NULL = N * ( character set:utf8=3,gbk=2,latin1=1)+1(NULL)+2(变长字段)
varchr(N)变长字段且不允许NULL = N * ( character set:utf8=3,gbk=2,latin1=1)+2(变长字段)
char(N)固定字段且允许NULL = N * ( character set:utf8=3,gbk=2,latin1=1)+1(NULL) char(N)固定字段且不允许NULL = N * ( character set:utf8=3,gbk=2,latin1=1)
数值数据的key_len计算公式:
TINYINT允许NULL = 1 + 1(NULL)
TINYINT不允许NULL = 1
SMALLINT允许为NULL = 2+1(NULL)
SMALLINT不允许为NULL = 2
INT允许为NULL = 4+1(NULL)
INT不允许为NULL = 4
日期时间型的key_len计算:(针对mysql5.5及之前版本)
DATETIME允许为NULL = 8 + 1(NULL)
DATETIME不允许为NULL = 8
TIMESTAMP允许为NULL = 4 + 1(NULL)
TIMESTAMP不允许为NULL = 4
3.索引使用有效方式
假设:联合索引类型(a,b,c)
正常使用语法方式:a>b>c, a>c>b, c>b>a, b>c>a, c>a>b, b>a>c均是有效的
例如:
EXPLAIN select * from user where pid = 100010 and name like '2000%' and user_no ='300010'
EXPLAIN select * from user where pid = 100010 and user_no ='300010' and name like '2000%'
EXPLAIN select * from user where name like '2000%' and user_no ='300010' and pid = 100010
EXPLAIN select * from user where user_no ='300010' and name like '2000%' and pid = 100010
EXPLAIN select * from user where name like '2000%' and pid = 100010 and user_no ='300010'
EXPLAIN select * from user where user_no ='300010' and pid = 100010 and name like '2000%'
这几个查询的结果,key_len长度均为133:
总结:索引最左边的参数存在的话,符合索引规则的语句就能使用索引
1.位置失效情况:
a>c: EXPLAIN select * from user where pid = 100010 and user_no ='300010'
结果如下:
总结:只有a用到索引
c>a: EXPLAIN select * from user where user_no ='300010' and pid = 100010
结果如下:
总结:只有a用到索引
a>b 或者 b>a: 均用到索引,例子省略
2.模糊查询失效:
%xxx 情况:EXPLAIN select * from user where name like '%2000' and pid = 100010
结果如下:
总结: 模糊索引失效,只有索引a有效
xxx% 情况:EXPLAIN select * from user where name like '2000%' and pid = 100010
结果如下:
总结:索引有效
3.条件查询失效:
1.查询数据量达到总数据量的30%左右就不会使用索引
2.如果有limit限制条数,则查询数据量达到总数据量的99.2%左右不会使用索引
4.<>或者!=失效:
EXPLAIN select * from user where name like '2000%' and pid != 100010
结果如下:
总结:索引失效
5.is null和 is not null :
EXPLAIN select * from user where name is not null and pid = 100010
结果如下:
总结:b索引失效,只有a成功
未完待续!!!