我有两个表 posts
和 posts_replies
我查询了所有帖子并按时间戳(发布时间)对它们进行排序。
现在我想做以下事情:
每当用户对任何帖子做出回复时,我都想将该帖子放在墙的顶部
所以我确实得到了每个帖子的最大回复时间戳,并使用特定帖子回复的最大时间戳对帖子进行排序。
问题是有些帖子没有任何回复,所以这篇帖子的最大 timestamp_of_replies 将为 NULL 所以我想知道:是否有可能在 timestamp_of_replies 不为 null 时按 timestamp_of_replies 排序结果,而在 timestamp_of_replies 为 null 时按 post_timestamp 排序结果空值。
我的查询:
SELECT
posts.*,
u1.id as user_id,
u1.avatar,
u1.username as poster_username,
u2.username as posted_username ,
posts.timestamp,
f1.recent_reply_time
FROM
posts
INNER JOIN
users u1
ON posts.poster_id = u1.id
INNER JOIN
users u2
ON posts.posted_id = u2.id
LEFT JOIN (
SELECT
max(timestamp) as recent_reply_time,
post_id
FROM
posts_replies
GROUP BY post_id) f1
ON f1.post_id = posts.id
order by
f1.recent_reply_time DESC
注意:order by f1.recent_reply_time, posts.timestamp DESC
没有给我正确的结果
最佳答案
MySQL 有一个 IF()
函数,您也可以在 ORDER BY
子句中使用:
ORDER BY IF(column IS NULL, othercolumn, column)
在你的情况下会是:
ORDER BY IF(f1.recent_reply_time IS NULL, posts.timestamp, f1.recent_reply_time)
关于mysql - 如果它的某些值是空的,如何按列排序查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21474996/