如何从最旧到最新订购的表中返回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
答案 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要求连接中的所有子查询都用别名命名。