A possible Optimization Method for mysql limit large offset

Source: Internet
Author: User

A possible Optimization Method for mysql limit large offset when the mysql limit statement is large in data volume, the offset after limit is too large, and the first query will be very slow, because mysql enables query cache by default, therefore, the second re-execution of the large offset query will not be affected. Example: for a table in 1 million, id is used as the primary key, auto_increment. Query required:

SELECT * FROM table ORDER BY id DESC LIMIT 990000,100

 

Relatively slow. The common method is:
SELECT * FROM table WHERE id >=(SELECT id FROM table ORDER BY id DESC LIMIT 990000,1) ORDER BY id DESC LIMIT 100

 

IDS may not be consecutive, and sorting may not depend solely on IDs. This method cannot be applied in actual projects. For example, there are complex sorting methods in our actual project:
ORDER BY (column1 + column2) * column3 DESC
And so on. For 1 million of data, if the offset is 990000, the reverse sorting should be closer to the header: --------------------------------------------------------- [0.99 million-| 100] -- 1 million needs to be implemented:
SELECT * FROM table ORDER BY columns DESC LIMIT 990000, 100

 

We can infer a solution: reverse sort, intercept the header, and reverse it again. The result is as follows:
$ Head = max (1 million-0.99 million-100, 0); SELECT * FROM (SELECT * FROM table order by columns asc limit $ head, 100) AS t order by columns DESC

 

The optimization is completed. The speed near the end is as fast as that at the beginning, but there is no difference if the offset in the middle is obtained.

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.