如何按日期返回最后5行

时间:2013-11-28 16:22:35

标签: php mysql

如何从最旧到最新订购​​的表中返回5个最近的行(按日期)。

$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 

1 个答案:

答案 0 :(得分:6)

使用子查询获取最新的行,然后在主查询中以其他方式对其进行排序。

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

要回答不可避免的问题,x是子查询的别名,因为MySQL要求连接中的所有子查询都用别名命名。