Reputation: 926
I'm trying to get a list of the n most recent entries into a database, but sort them ascending.
Obviously I can use the following to get the first n entries:
SELECT owner_id,message
FROM messages
WHERE thread_id = ?
ORDER BY time ASC
LIMIT ?
Or this to get the most 5 recent, descending:
SELECT owner_id,message
FROM messages
WHERE thread_id = ?
ORDER BY time DESC
LIMIT ?
But how can I get the most recent 5 in ascending order? I can just reverse the order of the array in PHP, but that seems a little inefficient.
Upvotes: 0
Views: 72
Reputation: 167
select owner_id,message from (
SELECT owner_id,message,time
FROM messages
WHERE thread_id = ?
ORDER BY `time` DESC
LIMIT ?
) temp
order by time ASC
Upvotes: 3
Reputation: 7123
Select * from
(SELECT owner_id,message,time
FROM messages
WHERE thread_id = ?
ORDER BY time DESC
LIMIT ?) test
Order by time ASC
Upvotes: 5