Retrieving the Last Row in MySQL
When working with MySQL tables, it can be necessary to access the last row inserted. This may be required to retrieve a column value or perform other operations based on the most recent data. In cases where the table includes an auto-increment field, identifying the last row becomes straightforward.
Using the Auto-Increment Field
The auto-increment field provides a unique identifier for each row in a table. By sorting the rows in descending order of this field and limiting the results to one, it is possible to select the last row inserted:
SELECT fields FROM table ORDER BY id DESC LIMIT 1;
This query retrieves the fields specified from the last row of the table. The id column must be an auto-increment field to ensure the proper ordering of rows.
Note: If the table includes multiple auto-increment fields, use the highest-valued field for descending ordering in the query.
The above is the detailed content of How Do I Retrieve the Last Inserted Row in MySQL?. For more information, please follow other related articles on the PHP Chinese website!