Home >Database >Mysql Tutorial >How to Reliably Select the Last N Rows in Ascending Order from a MySQL Table?
Selecting the Last N Rows from MySQL
Selecting the last N rows from a MySQL database can be a straightforward task using various methods. However, when dealing with primary key columns sorted in ascending order, conventional approaches may encounter limitations. This article aims to provide a reliable solution to this problem, allowing for manipulation and elimination of records within the table.
The Problem:
The original goal is to retrieve the last 50 rows from a table sorted in ascending order based on the primary key column id. However, the initial attempt highlighted two weaknesses:
The Solution:
To overcome these challenges, a more robust approach employs a sub-query:
SELECT * FROM ( SELECT * FROM table ORDER BY id DESC LIMIT 50 ) AS sub ORDER BY id ASC;
Explanation:
This approach effectively addresses the limitations encountered with conventional methods. It allows for:
The above is the detailed content of How to Reliably Select the Last N Rows in Ascending Order from a MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!