標籤:
先來說一下Mysql中limit的文法:
--文法:SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset
--舉例:select * from table limit 5; --返回前5行select * from table limit 0,5; --同上,返回前5行select * from table limit 5,10; --返回6-15行
Mysql中分頁主要利用limit能夠根據位移量返回結果的特性:
select ... from ... where ... order by ... desc limit pagesize * (page - 1), pagesize;--舉例:取t_u_coach表中按coachId降序排列後第5頁的教練列表,其中每頁10個教練select * from t_u_coach where id > 10000 order by coachId desc limit 40, 10;
在中小資料量的情況下,唯一需要注意的是coachId和id最好已經建立了彙總索引。
但是當資料量很大的時候,limit m,n 的效能隨著m的增加而急劇下降。比如:
--舉例:位移值過大的時候效能下降select * from t_u_coach where id > 10000 order by coachId desc limit 40000, 10;
此時,通常有兩種方法來進行最佳化:
一,使用子查詢的方式來進行分頁
select * from t_u_coach where coachId >= (select coachId from t_u_coach where id > 10000 order by coachId desc limit 40000, 1) limit 10;
二,使用join的方式來進行分頁
select * from t_u_coach as t1 join (select coachId from t_u_coach where id > 10000 order by coachId desc limit 40000, 1) as t2 where t1.coachId >= t2.coachId order by t1.coachId desc limit 10;
使用子查詢來進行分頁最佳化的時候,主要是因為能在子查詢中使用索引。
Mysql中的分頁處理