---
title: " 关于MySQL的LIMIT 语法小优化"
author: "piziwang"
date: "2010-04-28T09:19:06Z"
tags: ["Cache", "MySQL", "SQL", "XP"]
categories: ["数据库"]
slug: "mysql-limit"
draft: false
lastmod: "2010-04-28T09:19:06Z"
id: 654686
url: "https://piziwang.iteye.com/blog/654686"
---

下面我来举一个 简单的例子。  
考虑如下 表结构：  
/\*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;

&lt;!--&gt;

### query result(1 records)

count(\*) 993098

下面我们 来一步一步看看下面的这条语句：  
explain select sql\_no\_cache * from t\_page\_sample order by id asc limit 900001,20;  
&lt;!--&gt;  
&lt;!--&gt;

### 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 &gt;= ( 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。可喜可贺。

转自[CSDN](http://blog.csdn.net/yueliangdao0608/archive/2010/04/26/5530713.aspx "CSDN")