show create table 20130314t1
CREATE TABLE `20130314t1` (
`id` int(11) NOT NULL,
`col1` int(11) NOT NULL,
`col2` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `key1` (`col1`,`col2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
其中表里插入了100w数据,col1和col2都是100以内的随机数.
进行如下的查询,
select COUNT(*) from 20130314t1 where col1 >19 and col1 <30 and col2 >30 and col2 <33;
这是在多列索引上进行的range scan,理论上mysql只能使用索引的一部分,即col1那部分,从查询计划来看,key_len是4
mysqlslap工具测试下,平均时间是0.178s
把查询改成
select COUNT(*) from 20130314t1 where col1 BETWEEN 20 and 29 and col2 >30 and col2 <33;
这个非常奇怪,理论上key_len应该还是4,因为5.1的文档说
[quote]
If the operator is >, <, >=, <=, !=, <>, BETWEEN, or LIKE, the optimizer uses it but considers no more key parts.
[/quote]
结果key_len成了8,不过mysqlslap测试的结果提升不大,变成了0.156s
现在使用in语句,因为都是int类型,语句可以改成
select COUNT(*) from 20130314t1 where col1 in(20,21,22,23,24,25,26,27,28,29)
and col2 >30 and col2 <33
key_len还是8,不过变成了0.005s
这是因为col1 BETWEEN 20 and 29是range scan(范围扫描),
而col1 in(20,21,22,23,24,25,26,27,28,29)是多值相等,尽管结果一样,但是意义有着显著的不同.
可以通过show status like 'Handler_%';来观察三个语句执行中的读情况
select COUNT(*) from 20130314t1 where col1 >19 and col1 <30 and col2 >30 and col2 <33;
| Handler_read_key | 1 |
| Handler_read_next | 99856 |
select COUNT(*) from 20130314t1 where col1 BETWEEN 20 and 29 and col2 >30 and col2 <33;
| Handler_read_key | 1 |
| Handler_read_next | 90168 |
select COUNT(*) from 20130314t1 where col1 in(20,21,22,23,24,25,26,27,28,29)
and col2 >30 and col2 <33;
| Handler_read_key | 10 |
| Handler_read_next | 2072 |
看到使用了in之后,Handler_read_next变小了,说明按索引扫描的行明显变少了,所以有了提高.
本文通过对比不同查询条件对MySQL性能的影响,展示了如何利用索引优化查询效率。实验表明,在多列索引中使用IN语句相较于BETWEEN或范围查询能更有效地减少索引扫描行数,从而大幅提高查询速度。
524

被折叠的 条评论
为什么被折叠?



