SQL: select N “most recent” rows in ascending order
For example, if my data look like this:
timestamp | message 100 | hello 101 | world 102 | foo 103 | bar 104 | baz
How can I select the three m开发者_Python百科ost recent rows — 102, 103, 104 — in ascending order?
The obvious (to me) … LIMIT 3 ORDER BY timestamp DESC
will return the correct rows but the order is incorrect.
Use an inner select to select the correct rows, and an outer select to order them correctly:
SELECT timestamp, message
FROM
(
SELECT *
FROM your_table
ORDER BY timestamp DESC
LIMIT 3
) T1
ORDER BY timestamp
精彩评论