普通寫法:mysql
select * from t where sellerid=100 limit 100000,20
普通limit M,N的翻頁寫法,每每在越日後翻頁的過程當中速度越慢,緣由mysql會讀取表中的前M+N條數據, M越大,性能就越差:sql
優化寫法:性能
select t1.* from t t1, (select id from t sellerid=100 limit 100000,20) t2 where t1.id=t2.id;
優化後的翻頁寫法,先查詢翻頁中須要的N條數據的主鍵id,在根據主鍵id回表查詢所須要的N條數據,此過 程中查詢N條數據的主鍵ID在索引中完成優化
注意:須要在t表的sellerid字段上建立索引 create index ind_sellerid on t(sellerid);spa
案例以下:code
原始語句:blog
select id, ... from buyer where sellerId = 765922982 and gmt_modified >= '1970-01-01 08:00:00' and gmt_modified <= '2013-06-05 17:11:31' limit 255000, 5000 ;
優化後語句:索引
select t2.* from (select id from buyer where sellerId = 765922982 and gmt_modified >= '1970-01-01 08:00:00' and gmt_modified <= '2013-06-05 17:11:31' limit 255000, 5000)t1, buyer t2 where t1.id=t2.id ;