MySQL按另一个表的总和排序

时间:2014-07-30 20:23:15

标签: php mysql sql mysqli

我目前在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查询)我能够以最佳评级获得评论; 含义按每条评论的评级总和排序。

示例:

  • 评论X 2 upvotes 4 downvotes (总计-2)
  • 评论Y没有投票(总计0)
  • 评论Z有1个upvote(总计1个)

这些将会出现的顺序是:

  1. 评论Z
  2. 评论Y
  3. 评论X

2 个答案:

答案 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,并且将被正确排序。