2013-11-28 71 views
0

如何根據從最早到最新排序的表格返回最近5行(按日期)。如何按日期返回最後5行

I.E.

$query = mysqli_query($connect,"SELECT * FROM posts 
WHERE postid like '$topic_id' 
ORDER BY postdate DESC LIMIT 5"); 

返回:

reply 10 
reply 9 
reply 8 
reply 7 
reply 6 

和:

$query = mysqli_query($connect,"SELECT * FROM posts 
WHERE postid like '$topic_id' 
ORDER BY postdate ASC LIMIT 5"); 

返回:

reply 1 
reply 2 
reply 3 
reply 4 
reply 5 

如何退還?

reply 6 
reply 7 
reply 8 
reply 9 
reply 10 
+0

謝謝。那樣做了。 – user3005687

+0

另一種方法是使用:ORDER BY posts.postdate ASC LIMIT 5,10「); – user3005687

+0

如果你總是有10行,那麼這只是一個好處,@Barmar給出的答案更好,並且總是給出5個最新的行 – AeroX

回答

6

使用子查詢獲取最近的行,然後在主查詢中以其他方式對其進行排序。

SELECT * 
FROM (SELECT * FROM posts 
     WHERE postid like '$topic_id' 
     ORDER BY postdate DESC LIMIT 5) x 
ORDER BY postdate ASC 

要回答這個不可避免的問題,x是子查詢的別名,因爲MySQL需要的所有子查詢中加入與別名命名。

+1

簡單,優雅,並且很好的解釋。從我的+1。 –

+0

要看看x做了什麼,不用x – Strawberry

+0

@ user3005687試試這是否解決了問題?請接受答案。 – Barmar