Home > Database > Mysql Tutorial > How to Efficiently Retrieve the Last N Rows from MySQL in Ascending Order?

How to Efficiently Retrieve the Last N Rows from MySQL in Ascending Order?

Patricia Arquette
Release: 2024-12-13 16:53:15
Original
986 people have browsed it

How to Efficiently Retrieve the Last N Rows from MySQL in Ascending Order?

Retrieving the Last N Rows from MySQL in Ascending Order

Retrieving the last N rows from a MySQL database can be a common task, especially when working with large tables. However, ordering the results in ascending order while ensuring the integrity of the data, can become a challenge.

Consider the following query:

SELECT 
    *
FROM
    `table`
ORDER BY id DESC
LIMIT 50;
Copy after login

At first glance, this query appears to select the last 50 rows. However, it does so in descending order (from greatest to least), which violates the requirement for ascending order.

Another approach is:

SELECT 
    *
FROM
    `table`
WHERE
    id > ((SELECT 
            MAX(id)
        FROM
            chat) - 50)
ORDER BY id ASC;
Copy after login

This query aims to retrieve rows with IDs greater than the maximum ID minus 50. However, it also fails because the data is subject to manipulation, and rows could be deleted, potentially affecting the results.

Solution: Subquery Approach

To address these challenges, a subquery can be employed:

SELECT * FROM
(
 SELECT * FROM table ORDER BY id DESC LIMIT 50
) AS sub
ORDER BY id ASC;
Copy after login

This query involves a subquery that selects the last 50 rows in descending order. The results of this subquery are then stored in a temporary table called "sub." Finally, the outer query selects all rows from "sub" and orders them in ascending order.

This approach ensures that the last 50 rows are selected, even if the table is manipulated, and the results are presented in ascending order.

The above is the detailed content of How to Efficiently Retrieve the Last N Rows from MySQL in Ascending Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template