MySQL order by id 也会有不走索引

我在网上找了半天一直疑问着, 不知为什么??

 

但答案找到了, 呵呵。。让我心里解开了

 

 

<!-->

query result(1 records)

count(*)
993098


下面我们 来一步一步看看下面的这条语句:
explain select sql_no_cache * from t_page_sample order by id asc limit 900001,20; 
<!-->
<!-->

query result(1 records)

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEt_page_sampleALL(NULL)(NULL)(NULL)(NULL)993098Using filesort


从 上面可以看出,她没有用到任何索引,扫描的行数为993098,而且用到了排序!

select sql_no_cache * from t_page_sample order by id asc limit 900001,20; 

(20 row(s)returned) 

(4688 ms taken)

 

 

那么我们怎么优化这条语句呢?
首先,我们想到的是索引。 在这条语句中,只有ID可能能用到索引,那么我们给优化器加一个暗示条件,让他用到索引。


select sql_no_cache * from t_page_sample force index (primary) order by id asc limit 900001,20; 

(20 row(s)returned) 
(9239 ms taken) 

没想到用的时间竟然比不加索引还长。 看来这条路好像走不通了。
我们尝试着变化下语句如下: 
select * from t_page_sample 
where id between 
         (select sql_no_cache id from t_page_sample order by id asc limit 900001,1)
         and 
         (select sql_no_cache id from t_page_sample order by id asc limit 900020,1); 

(20 row(s)returned)
 
(625 ms taken) 
哇,这个很不错,足足缩短了将近15倍! 
那么还有优化的空间吗? 
我 们再次变化语句: 
select * from t_page_sample 
where id >= ( select sql_no_cache id from t_page_sample order by id asc limit 900001,1) 

limit 20; 

(20 row(s)returned) 
(406 ms taken) 

时间上又比上次的语句缩短了1/3。可喜可贺。

 

 

 

http://www.cnblogs.com/phper7/archive/2010/05/14/1735069.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值