Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4153279
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类: Mysql/postgreSQL

2010-04-26 16:16:33

    今天有朋友问起此类语句的优化,我大致给他介绍了下从SQL角度做简单的优化,至于应用程序方面的考虑咱暂时不考虑。
下面我来举一个简单的例子。
考虑如下表结构:
/*DDL Information For - t_girl.t_page_sample*/
----------------------------------------------

Table          Create Table                                                    
-------------  ----------------------------------------------------------------
t_page_sample  CREATE TABLE `t_page_sample` (                                  
                 `id` int(10) unsigned NOT NULL,                               
                 `v_state` tinyint(1) NOT NULL DEFAULT '1',                    
                 `log_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',  
                 `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,   
                 PRIMARY KEY (`id`)                                            
               ) ENGINE=MyISAM DEFAULT CHARSET=utf8

我的测试系统为标配DELL D630, XP系统。
示例表的记录数:
select count(*) from t_page_sample;

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)

id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t_page_sample ALL (NULL) (NULL) (NULL) (NULL) 993098 Using 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。可喜可贺。



阅读(5552) | 评论(7) | 转发(0) |
给主人留下些什么吧!~~

zhengwei_zw2011-04-16 18:51:06

where id>900001 limit 20 效率比楼主的还要高的。 呵呵

chinaunix网友2010-12-12 14:28:30

修改之后的语句没有对结果进行排序,排序是比较花时间的。

chinaunix网友2010-07-01 16:35:16

很少评论博客的... 偶然看到你的博客 打算从头到尾一篇篇看完..收获很大啊..

chinaunix网友2010-05-16 10:14:22

问下你这个MS时间是怎么得出的?

chinaunix网友2010-05-05 23:35:35

说白了,您就是让引擎使用索引来优化这个sql语句。 这句sql使用了id列上的主键,select sql_no_cache id from t_page_sample order by id asc limit 900001,1 而select sql_no_cache * from t_page_sample order by id asc limit 900001,20; 却是表扫描。 问题在于id和* 决定了是否选择使用索引。 至于后面的继续优化,是between and 和id》=的问题。 自然后者的效率高些。