MySQL efficient paging: subquery Paging

Source: Internet
Author: User

Generally, the most basic paging method of MySQL is as follows:

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

In the case of small data volumes, such SQL statements are enough. The only problem that needs to be paid attention is that indexes are used. As the amount of data increases, the number of pages will increase. The SQL statements on the last few pages may be similar:

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

In a word, the more paging goes, the larger the offset of the limit statement, and the slower the speed.

In this case, we can use two methods:
1. The paging method of subqueries improves paging efficiency. The SQL statements that are easy to use are as follows:

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

After easy measurement, the efficiency of the subquery paging method is 14-20 times higher than that of the pure limit method!

Ii. Join paging Mode

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; 

In my tests, the efficiency of join paging and subquery paging is basically at the same level, and the consumed time is basically the same. Explain SQL statement:

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra1PRIMARY<derived2>systemNULLNULLNULLNULL1 1PRIMARYt1rangePRIMARYPRIMARY4NULL6264Using where2DERIVEDcontentindexNULLPRIMARY4NULL27085Using index

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.