MySQL命令帖子按最新评论或最后发布

时间:2013-11-17 06:55:54

标签: mysql sql select sql-order-by

如何对帖子进行排序,以便将最近的活动排在最前面?

# Schema not including all info, including FKs
CREATE TABLE post(
   id int unsigned primary key auto_increment,
   msg text,
   created datetime
)ENGINE=InnoDb;

CREATE TABLE comment(
   id int unsigned primary key auto_increment,
   post_id int unsigned,
   msg text,
   created datetime
)ENGINE=InnoDb;

我想订购最近发布的帖子,其中新帖子显然比之前发布的帖子更新,但是最近发表评论的旧帖子仍然属于最新评论。

第一次尝试

# Selecting '*' for simplicity in this example
select *
from post p
left join comment c on c.post_id = p.id
group by p.id
order by c.created desc, p.created desc

这不起作用,因为新帖子会在带有评论的旧帖子之后进行排序。

第二次尝试

select *, if(c.id is null, p.created, c.created) as recency
from post p
left join comment c on c.post_id = p.id
group by p.id
order by recency desc

不起作用,因为如果帖子有多个评论,新近度将匹配第一行的创建的值,这是最早的评论。< / p>

* 是否有通过p.id 分组的方法(因此只选择了每个帖子的一个副本),但每个组内的排序是通过c.date desc,但查询顺序by是通过新近度完成的?如果没有将更新的字段添加到 post ,我无法想到这样做的方法,每当发布回复时我都会写这个...

谢谢!

1 个答案:

答案 0 :(得分:4)

这应该这样做:

SELECT p.id
FROM post p
    LEFT JOIN comment c on c.post_id = p.id
GROUP BY p.id
ORDER BY COALESCE(GREATEST(p.created, MAX(c.created)), p.created) DESC

如果我们假设评论总是比帖子旧,我们可以简化:

SELECT p.id
FROM post p
    LEFT JOIN comment c on c.post_id = p.id
GROUP BY p.id
ORDER BY COALESCE(MAX(c.created), p.created) DESC