如果某些值为null,如何按列排序查询?

时间:2014-01-31 07:55:20

标签: mysql sql query-optimization

我有两个表postsposts_replies我查询了所有帖子并按时间戳(发布时间)排序。 现在我想做以下事情: 每当用户对任何帖子做出回复时,我都希望将该帖子放在墙上 所以我确实得到了最大的回复#39;每个帖子的时间戳,并使用特定帖子的回复的最大时间戳订购帖子。

问题是某些帖子没有任何回复所以这篇文章的最大timestamp_of_replies将为NULL所以我想知道:当它不为空时,是否可以通过timestamp_of_replies对结果进行排序;当它是非空时,可以通过post_timestamp对结果进行排序NULL。

我的查询:

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没有给我正确的结果

3 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:0)

SORTING易于阅读和维护,如果您根据自己选择的内容制作它。最好在您的选择中添加一些sortkey并在ORDER BY中使用它。

我使用COALESCE来处理空值。通过使用适当的COALESCE参数,使至少具有一个NOT NULL值的排序键

 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,
       COALESCE(f1.recent_reply_time,posts.timestamp) as sortkey
    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 sortkey DESC

答案 2 :(得分:0)

使用COALESCE:

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 COALESCE(f1.recent_reply_time,[alternative value (CURDATE())]) DESC