mysql limit語句優化

markzy5201190發表於2013-06-07
形如下表:
CREATE TABLE `tbl` (                                 
`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;

初始化20w條資料;

mysql> explain SELECT SQL_NO_CACHE * from tbl ORDER BY id ASC LIMIT 99999,20 \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tbl
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 99999
        Extra: Using filesort
1 row in set (0.00 sec)

ERROR:
No query specified

從上面看沒有用到索引,掃描了99999行,且還用到了排序;

對應轉換sql如下:

mysql>explain
select *
from tbl
where id>=(
select SQL_NO_CACHE id from tbl order by id asc limit 99999,1)limit 20 \G;

相對而言,執行消耗時間比直接limit要少;



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26855487/viewspace-763406/,如需轉載,請註明出處,否則將追究法律責任。

相關文章