2014-01-25 47 views
0

我试图获取n个最近的条目到数据库中的列表,但按升序排序。MySQL最近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中颠倒数组的顺序,但这似乎有点低效。

回答

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

+0

谢谢,这看起来是在正确的轨道上,但我从中得到错误。当我尝试访问测试别名的时间列时,我被告知“'order clause'中的未知列时间''。我试图访问它作为test.time,但MySQL不会接受。 – nathan

+0

编辑。现在看。你应该在临时结果集中获得时间字段 –

+0

哈哈,我想我应该能够自己找出那一个。谢谢! – nathan

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 
+0

你说得对,现在没关系。 – immo

+0

错误,错误,错误.... :)现在它工作正常 – immo