5 methods of MySQL pagination query

Method 1:

select * from table order by id limit m, n;

Very simple, the meaning of this statement is to query m+n records, remove the first m records, and return the last n records. Undoubtedly, the query can achieve pagination, but the larger m is, the lower the query performance is, because MySQL needs to scan all m+n records.

Method 2:

select * from table where id > #max_id# order by id limit n;

This query will also return the last n records, but there is no need to scan the first m records like method 1, but it is more common to get the maximum id (or minimum id) of the previous query (previous page) in each query The way.

Of course, the problem with this query is that we may not be able to get this id. For example, if we are currently on page 3 and need to query the data on page 5, it will not work.

Method 3:

In order to avoid cross-page queries that cannot be realized in method 2, it is necessary to combine method 1.

Performance needs, m should be as small as possible. For example, if you are currently on page 3, you need to query page 5, with 10 pieces of data per page, and the maximum id of page 3 is #max_id#, then:

select * from table where id > #max_id# order by id limit 10, 10;

This method partially solves the problem of method 2, but if you are currently on page 2 and want to check page 1000, the performance is still poor.

Method 4:

select * from table as a inner join (select id from table order by id limit m, n) as b on a.id = b.id order by a.id;

This query is the same as method 1, and the value of m may be very large, but because the internal subquery only scans the id field instead of the entire table, the performance is stronger than method 1, and it can solve the cross-page query problem.

Method 5:

select * from table where id > (select id from table order by id limit m, 1) limit n;

This query also scans the field id through the subquery, and the effect is the same as that of method 4. However, the performance of method 5 is slightly better than that of method 4, because it does not require table association, but a simple comparison. It is a recommended usage when the maximum id of the previous page is not known.

Guess you like

Origin blog.csdn.net/std7879/article/details/125308628