MySQL SQL getting most recent records in a table?
I have an sql statement as below attempting to retrieve the most recent entries in a table. I have two questions:
Is it better to order by id or by date?
How do I rewrite this sql statement to re-order by date?
SELECT id, comment, DATE_FORMAT(entry_da开发者_Python百科te, '%W %H:%i') FROM comments ORDER BY id DESC LIMIT 10
It depends on what you mean by most recent:
If you mean the most recently created record, then (in most cases) by primary key id will work.
If you mean the most recently updated record, then definitely by date.
To sort by date just change the field name: ORDER BY entry_date DESC
If you have to be 100% precise to sort for the newest rows, you must use the date field. Sorting for the time field when you want to sort for the newest makes pretty much sense and if indexed, sorting on dates will take the same time than to sort for the id-s.
The values for the id field are only guaranteed to be unique I assume, there is possibly no way to ensure that they are ordered by insertion time. For example the id field can be a cyclic field (6,7,8,-7,-6...), or a later modification on the table is allowed to change the id fields but will not know to preserve their ordering by insertion time, or parallel transactions might decide to insert new rows in a different order on the id and date fields.
精彩评论