mysql选择联合索引还是单索引?索引列应该使用哪一个最有效?深入测试探讨 先建表 create table `menu_employee` ( `id` int(11) not null auto_increment comment '自增主键,无实际意义', `employee_pid` int(5) default null comment '父节点序号,一般是
mysql选择联合索引还是单索引?索引列应该使用哪一个最有效?深入测试探讨
先建表
create table `menu_employee` (
`id` int(11) not null auto_increment comment '自增主键,无实际意义',
`employee_pid` int(5) default null comment '父节点序号,一般是部门的序号,但是已有例外,没有组的员工',
`employee_id` int(5) default null comment '员工序号,相应的部门序号+员工序号',
`employee_name` varchar(100) default '' comment '员工名称',
`action` varchar(100) default null comment 'action事件路径',
primary key (`id`),
key`x` (`employee_id`,`employee_pid`) using btree
) engine=myisam auto_increment=38 defaultcharset=utf8 comment='员工表'
数据自己添加.
好,开始测试:
写一个sql,来跑一下试试
explain
select
employee_name
from
menu_employee
force index ( x )
where
employee_id> 3
and
employee_pid> 20
order by
employee_pid
建一个索引,按照黄金律,把where跟着了,一起建一个联合索引.
结果是:
是不是很奇怪,明明了用了索引了,可是却依然是 using filesort!
好,接着我们改回单索引
再看结果:
是不是很神奇?
再试一下,那我们如果把索引列换成employee_id会肿么样呢,我们来试一试,
居然没有什么效果,还是using filesort!
单索引比复合索引有效果!而且还要选对要索引的列!
接下来说复合索引
先建表:
create table `l_insertlogs` (
`id` int(10) not null auto_increment,
`counts` int(10) default null,
`tablesname` char(30) default null,
`operatetime` datetime default null,
primary key (`id`),
key`x` (`counts`,`id`) using btree
) engine=innodb auto_increment=6155 defaultcharset=utf8
跑一下:
explain
select
tablesname
from
l_insertlogs
force index ( x )
where
idbetween 100 and 500
and
counts> 14
order by
counts
再来个索引,来一个复合双索引
结果一点也不好看
再试试,改成单的,用主键做列
还是不行
改成
这下就行了
所以说,双索引不一定有效,怎么使用要看实际情况,索引使用哪一列也是很讲究的,这还是只是表现,我还要接着深挖下去.