【问题标题】:MySQL Order by sum of another tableMySQL 按另一个表的总和排序
【发布时间】:2014-09-22 15:36:31
【问题描述】:

我目前在 mysql 中有 2 个表; cmetscomment_rating

comment_rating 具有以下结构:

+------------+
| Field      |
+------------+
| id         |
| comment_id |
| user_id    |
| positive   |
| created_at |
+------------+

positive 字段为 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 查询)我能够获得按最佳评级排序的 cmets; 含义按每条评论的评分总和排序。

例子:

  • 评论 X 有 2 个赞成票4 个反对票(总共 -2 个)
  • 评论 Y 无票(共 0 票)
  • 评论 Z 有 1 个赞(总共 1 个)

这些出来的顺序是:

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

【问题讨论】:

  • 使用SUM 而不是COUNT

标签: php mysql sql mysqli


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2020-09-08
      • 2021-03-27
      相关资源
      最近更新 更多