mysql - 如果它的某些值是空的,如何按列排序查询?

标签 mysql sql query-optimization

我有两个表 postsposts_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/

相关文章:

SQL:查找具有重复值的最小、最大日期

mysql - 需要对索引进行一些说明(WHERE、JOIN)

SQL函数来计算字符串在列中出现的次数?

mysql - SQL auto_increment 行为

sql - 带有 IN 的 postgres 查询非常慢

javascript - 哪一种是在 mysql 中删除和更新查询的最佳方法?

php - 为什么这个 SQL 查询会杀死我的服务器?

需要 MySQL 查询优化提示

mysql - <= 在mysql查询中显示<的记录

php - 在 FullCalendar 中查看按事件 ID(而不是开始时间戳)排序的事件