我目前在mysql中有2个表; 评论 和 comment_rating
comment_rating 具有以下结构:
+------------+
| Field |
+------------+
| id |
| comment_id |
| user_id |
| positive |
| created_at |
+------------+
场强为 1 或 -1 1为正(向上投票),-1为负(投票)
我有这个当前的查询,这将得到我评论最多评分:
SELECT *, COUNT(comment_rating.id) AS rating_count FROM comments LEFT JOIN comment_rating ON comments.id = comment_rating.comment_id GROUP BY comments.id ORDER BY rating_count DESC
我需要知道如何(使用mysql查询)我能够以最佳评级获得评论; 含义按每条评论的评级总和排序。
示例:
这些将会出现的顺序是:
答案 0 :(得分:4)
SELECT comments.id,
COUNT(comment_rating.id) AS rating_count,
sum(positive) as rating
FROM comments
LEFT JOIN comment_rating ON comments.id = comment_rating.comment_id
GROUP BY comments.id
ORDER BY rating DESC
答案 1 :(得分:1)
谢谢 juergen d
您的查询几乎完美:
这是一个稍微修改过的版本,可以正确地进行排序:
SELECT comments.id,
COUNT(comment_rating.id) AS rating_count,
COALESCE(SUM(positive),0) as rating
FROM comments
LEFT JOIN comment_rating ON comments.id = comment_rating.comment_id
GROUP BY comments.id
ORDER BY rating DESC
这样,如果行不存在,它将被设置为零而不是null,并且将被正确排序。