Mysql索引的使用

来源:互联网 发布:cdma网络是什么意思 编辑:程序博客网 时间:2024/06/06 01:26
结果是:KEY(key_part1,key_part2,key_part3)
select .... from table where key_part1='xxx' and key_part3='yyy'; 
在这种情况下,MYSQL只能在索引里处理掉key_par1,而不过在索引里过滤 key_part3的条件,除非 select 后面是 count(*) ;
[@more@]


这是上次测试时的表结构:
CREATE TABLE `im_message_201005_21_old` (
`msg_id` bigint(20) NOT NULL default '0',
`time` datetime NOT NULL,
`owner` varchar(64) NOT NULL,
`other` varchar(64) NOT NULL,
`content` varchar(8000) default NULL,
PRIMARY KEY (`msg_id`),
KEY `im_msg_own_oth_tim_ind` (`owner`,`other`,`time`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_bin;

这次我们要测试的是,先有范围字段的条件,MYSQL是不是能正确使用索引有效地过滤无效数据;
首先我们把索引的顺序调整一下:KEY `im_msg_own_tim_oth_ind` (`owner`,`time`,`other`)

我们要测试的是当where 条件是: owner+time+other 时, 索引的工作情况如何?
(大家不如先根据自己的知识下个定论?)

我觉得大部分同学认为,字段都一样,索引应该是能正常工作的。 实际是不然。

这个测试关键是想看看, 当查询条件是 owner+time+other 时 , mysql 能不能在回表前,把other字段进行过滤;
如果不能过滤,他将与条件是 owner+time 时,产生的性能(逻辑读)是差不多的;


select count(distinct content ) from im_message_201005_21_old 
where owner = 'cntaobaoytazy' and time >= '2010-05-23 17:14:23' and time <= '2010-05-30 17:14:23' ; 
# 结果: 4712行
# 产生逻辑读:27625

select count(distinct content ) from im_message_201005_21_old 
where owner = 'cntaobaoytazy' and time >= '2010-05-23 17:14:23' and time <= '2010-05-30 17:14:23'
and other = 'cnalichnahappycow' ;
# 结果:0行
# 产生逻辑读:25516


select count(* ) from im_message_201005_21_old 
where owner = 'cntaobaoytazy' and time >= '2010-05-23 17:14:23' and time <= '2010-05-30 17:14:23' ; 
# 结果: 4712 
# 产生逻辑读: 966

select count(* ) from im_message_201005_21_old 
where owner = 'cntaobaoytazy' and time >= '2010-05-23 17:14:23' and time <= '2010-05-30 17:14:23' 
and other = 'cnalichnahappycow' ; 
# 结果:0 
# 产生逻辑读: 966


从中我们发现 ,count(*)这种情况,只需要通过索引去过滤,不需要回表,逻辑读966; 这是比较合理的值;
而第二个语句,虽然返回结果是0行,但使用了与第一个语句相当的逻辑读 ; 显然,MYSQL没有合理使用索引 ;

总结一下: 
MYSQL在碰到复合索引时,只要碰到范围(<,>,<=,>=)的查询字段,过滤该条件后就去回表了,不管后面的字段有没有可以索引可以走。

0 0
原创粉丝点击