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