Mysql中的分頁處理

來源:互聯網
上載者:User

標籤:

先來說一下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中的分頁處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.