Mysql索引的使用 - 组合索引 + 范围条件的处理 超、凢脫俗 2021-06-24 14:37 500阅读 0赞 结果是: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在碰到复合索引时,只要碰到范围(<,>,<=,>=)的查询字段,过滤该条件后就去回表了,不管后面的字段有没有可以索引可以走。
还没有评论,来说两句吧...