SELECT p.*,
u.user_id,
u.user_name,
count(c.comment_post_id) AS comments
FROM posts AS p
LEFT JOIN comments AS c
ON (p.post_id = c.comment_post_id)
LEFT JOIN users AS u
ON (p.postedby_id = u.user_id)
WHERE c.comment_added > NOW() - INTERVAL 1 HOUR
GROUP BY p.post_id
ORDER BY count(c.comment_post_id) DESC
这会在过去一小时内按大部分评论排序的帖子列表。现在的问题是,上个小时有0个评论的帖子没有列表。
那么有没有办法让自评论创建以来每小时的平均评论排序?通过这种方式,所有帖子都会成为列表,并且讨论最多的帖子将始终排在最前面。
http://sqlfiddle.com/#!9/820044/1/0
编辑:
SELECT p.*, u.user_id, u.user_name, COUNT(c.comment_post_id) / (TIMESTAMPDIFF(HOUR, p.post_timestamp, SYSDATE()) + 1) AS rate FROM posts AS p LEFT JOIN comments AS c ON (p.post_id = c.comment_post_id) LEFT JOIN users AS u ON (p.postedby_id = u.user_id) GROUP BY p.post_id ORDER BY COUNT(c.comment_post_id) / (TIMESTAMPDIFF(HOUR, p.post_timestamp, SYSDATE()) + 1) DESC
这就解决了这个问题。
答案 0 :(得分:0)
在没有数据的情况下很难看到,但为了解决您的直接问题(即显示零最近评论帖子),您是否只想将约束移动到LEFT JOIN
?
LEFT JOIN comments AS c
ON (p.post_id = c.comment_post_id AND c.comment_added > NOW - INTERVAL 1 HOUR)
答案 1 :(得分:0)
由于WHERE
子句,您只选择在一小时内发表评论的帖子。您可以尝试的是:
SELECT p.*,
u.user_id,
u.user_name,
SUM(c.comment_added > NOW() - INTERVAL 1 HOUR) AS comments
FROM posts AS p
LEFT JOIN comments AS c
ON (p.post_id = c.comment_post_id)
LEFT JOIN users AS u
ON (p.postedby_id = u.user_id)
GROUP BY p.post_id
ORDER BY
COUNT(c.comment_post_id) /
(TIMESTAMPDIFF(HOUR, p.post_timestamp, SYSDATE()) + 1) DESC
对于小时内的每个评论,布尔表达式c.comment_added > NOW() - INTERVAL 1 HOUR
将为SUM(...)
贡献一个。
对于第二部分,我们可以找到使用TIMESTAMPDIFF(HOUR, p.post_timestamp, SYSDATE())
发布帖子所经过的小时数。因此,将评论数量与小时数相除,为我们提供了排序标准。但是我们在几个小时内添加一个以避免被零除。