The content is organized in GitHub, address https://github.com/Musleape/TestDemoProjects
MySQL pagination query
Usage of limit
- The limit clause can be used to force the select statement to return the specified number of records;
Accepts 1 or 2 integer constants as parameters, the first is the offset of the returned record row , and the second is the maximum number of returned record rows
-- 检索记录行6~15; mysql> SELECT * FROM table LIMIT 5,10; -- 从某个偏移量到记录集的最后,可以指定第二个参数为-1; mysql> SELECT * FROM table LIMIT 95,-1; -- 如果只给定一个参数,表示返回的作答记录行数目; mysql> SELECT * FROM table LIMIT 5; -- LIMIT n 等价于 LIMIT 0,n;
Performance Analysis of MySQL Paging Query Statement
Make sure to use an index, the following statement creates an index on the ta_id and id columns
mysql> SELECT * FROM ta WHERE ta_id = 111 ORDER BY id LIMIT 50,10;
Using subqueries , as the amount of data increases, the offset of the LIMIT statement will be larger and the speed will be significantly slower;
-- 使用子查询之前,偏移量为10000; mysql> SELECT * FROM ta WHERE ta_id = 123 ORDER BY id LIMIT 10000, 10; -- 使用子查询之后; mysql> SELECT * FROM ta WHERE id >= (SELECT id FROM ta WHERE ta_id = 111 ORDER BY id LIMIT 10000,1) LIMIT 10;
For MySQL tables with large amounts of data, LIMIT paging has serious performance problems:
Optimization method:
- Use subqueries
- Use a similar strategy mode to process paging, and judge that the basic paging method is used within 100 pages, and the sub-query paging method is used for more than 100 pages;
- Order by operation using indexed columns or primary key columns
- Record the primary key returned last time, and use the primary key to filter the next query
- In order to ensure that the index index column is continuous, you can add an auto-incrementing field to each table and add an index