SELECT p.*, u.user_id, u.user_name,
COUNT(c.comment_id) AS count,
COUNT(v.vote_post_id) /
(TIMESTAMPDIFF(MINUTE, v.vote_timestamp, SYSDATE()) + 1) AS rate
FROM posts AS p
LEFT JOIN comments AS c ON (p.post_id = c.comment_post_id)
LEFT JOIN post_votes AS v ON (p.post_id = v.vote_post_id)
LEFT JOIN users AS u ON (p.postedby_id = u.user_id)
GROUP BY p.post_id
ORDER BY COUNT(v.vote_post_id) /
(TIMESTAMPDIFF(MINUTE, v.vote_timestamp, SYSDATE()) + 1) DESC
这是我正在处理的脚本。我没有很好地填充我的数据库用于测试,但前两个结果得到了双倍的评论。你能在这里看到任何明显的错误吗?我有另一个版本的脚本在这里工作正常:
SELECT p.*, u.user_id, u.user_name,
COUNT(c.comment_id) AS count
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(MINUTE, p.post_timestamp, SYSDATE()) + 1) DESC
答案 0 :(得分:1)
多次投票会导致您的评论重复。如果您post_votes
GROUP BY
,您希望在vote_post_id
表格上进行子选择,以便将每个帖子的总投票数作为单个值。
由于COUNT
是保留字,因此我不建议将其用作结果集中的列名。
如果您只是收到评论计数而不是评论本身,那么您也会想要在子选择中,或者您将在帖子上加倍。
SELECT p.*, u.user_id, u.user_name, c.comment_count,
v.vote_count AS total_votes,
v.vote_count / (TIMESTAMPDIFF(MINUTE, p.post_timestamp, SYSDATE()) + 1) as votes_per_minute
FROM posts AS p
LEFT JOIN (SELECT comment_post_id, COUNT(comment_post_id) AS comment_count FROM comments GROUP BY comment_post_id) AS c ON (p.post_id = c.comment_post_id)
LEFT JOIN (SELECT vote_post_id, COUNT(vote_post_id) AS vote_count FROM post_votes GROUP BY vote_post_id) AS v ON (p.post_id = v.vote_post_id)
LEFT JOIN users AS u ON (p.postedby_id = u.user_id) GROUP BY p.post_id
ORDER BY v.vote_count / (TIMESTAMPDIFF(MINUTE, p.post_timestamp, SYSDATE()) + 1) DESC
答案 1 :(得分:0)
显然,您使用的是MYSQL,因为它是唯一允许此类组的数据库。然而,百分之百的时间使用它是一个糟糕的选择。您应该按照所有其他数据库所需的方式将选择中不属于聚合函数的所有字段分组。这是一个群体需要如何工作。这可能会解决您的问题。它可能不依赖于数据。如果某些连接表中有多个记录,并且它们在某些字段中碰巧有不同的数据,则在正确分组时仍可能无法获得一条记录。在这种情况下,您需要为连接编写派生表,或者在具有多个值的字段上使用聚合来告诉数据库使用哪个值。