MySQL高效分頁:子查詢分頁

來源:互聯網
上載者:User

一般MYSQL最基本的分頁方式:

select * from content order by id desc limit 0, 10

在中小資料量的情況下,這樣的SQL足夠用了,唯一需要注意的問題就是確保使用了索引。隨著資料量的增加,頁數會越來越多,查看後幾頁的SQL就可能類似:

select * from content order by id desc limit 10000, 10

一言以蔽之,就是越往後分頁,LIMIT語句的位移量就會越大,速度也會明顯變慢。

此時,我們可以通過2種方式:
一,子查詢的分頁方式來提高分頁效率,飄易用的SQL語句如下:

SELECT * FROM `content` WHERE id <= (SELECT id FROM `content` ORDER BY id desc LIMIT ".($page-1)*$pagesize.", 1) ORDER BY id desc LIMIT $pagesize

經過飄易的實測,使用子查詢的分頁方式的效率比純LIMIT提高了14-20倍!

二,JOIN分頁方式

SELECT * FROM `content` AS t1 JOIN (SELECT id FROM `content` ORDER BY id desc LIMIT ".($page-1)*$pagesize.", 1) AS t2 WHERE t1.id <= t2.id ORDER BY t1.id desc LIMIT $pagesize; 

經過我的測試,join分頁和子查詢分頁的效率基本在一個等級上,消耗的時間也基本一致。explain SQL語句:

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra1PRIMARY<derived2>systemNULLNULLNULLNULL1 1PRIMARYt1rangePRIMARYPRIMARY4NULL6264Using where2DERIVEDcontentindexNULLPRIMARY4NULL27085Using index

轉帖:http://www.piaoyi.org/php/MySQL-SUBQUERY-index.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.