Mysql索引怎么用

47次阅读
没有评论

共计 1708 个字符,预计需要花费 5 分钟才能阅读完成。

这篇文章主要为大家展示了“Mysql 索引怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让丸趣 TV 小编带领大家一起研究并学习一下“Mysql 索引怎么用”这篇文章吧。

select …. from table where key_part1= xxx and key_part3= yyy
在这种情况下,MYSQL 只能在索引里处理掉 key_par1,而不过在索引里过滤 key_part3 的条件,除非 select 后面是 count(*) ;

这是上次测试时的表结构:
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 索引怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注丸趣 TV 行业资讯频道!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-26发表,共计1708字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)