MySQL最近n个条目,升序?

时间:2014-01-25 17:33:57

标签: mysql sql sql-order-by

我正在尝试将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中反转数组的顺序,但这看起来效率不高。

2 个答案:

答案 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