关于MySQL的LIMIT 语法小优化!
2010-05-14 02:10
351 查看
<!-->
下面我们 来一步一步看看下面的这条语句:
explain select sql_no_cache * from t_page_sample order by id asc limit 900001,20;
<!-->
<!-->
从 上面可以看出,她没有用到任何索引,扫描的行数为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。可喜可贺。
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 |
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。可喜可贺。
相关文章推荐
- 关于MySQL的LIMIT 语法小优化!
- 关于MySQL的LIMIT 语法小优化!
- 关于MySQL的LIMIT 语法小优化!(这个很不错)
- 关于MySQL的LIMIT 语法小优化
- 关于MySQL的LIMIT 语法小优化!
- 关于MySQL的LIMIT 语法小优化!
- 关于MySQL的LIMIT 语法小优化!
- MYSQL关于limit优化问题
- MySQL关于分页较多的情况的优化limit xxxx,xx
- 关于MySQL的limit优化
- 关于mysql表中有大文本limit慢的优化
- 关于mysql的limit用于分页查询的优化
- MySQL技巧:做好Limit优化
- mysql limit分页优化方法
- 关于MYSQL的LIMIT使用变量
- MySql查询优化 百万级记录查询优化 limit分页查询
- Mysql limit 查询性能优化
- 高性能MySql设计之查询优化(limit优化)
- MYSQL查询优化:Limit
- 对mysql的order by及limit优化要适数据情况而定