我正在尝试将n个最近的条目列表添加到数据库中,但是将它们按升序排序。
显然我可以使用以下内容来获得前n个条目:
SELECT owner_id,message
FROM messages
WHERE thread_id = ?
ORDER BY time ASC
LIMIT ?
或者这可以获得最近的5个,降序:
SELECT owner_id,message
FROM messages
WHERE thread_id = ?
ORDER BY time DESC
LIMIT ?
但是如何以升序排列最近的5?我可以在PHP中反转数组的顺序,但这看起来效率不高。
答案 0 :(得分:5)
Select * from
(SELECT owner_id,message,time
FROM messages
WHERE thread_id = ?
ORDER BY time DESC
LIMIT ?) test
Order by time ASC
<强> Sample fiddle 强>
答案 1 :(得分:3)
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