gpt4 book ai didi

php - MySQL按另一个表的总和排序

转载 作者:行者123 更新时间:2023-11-29 04:20:43 25 4
gpt4 key购买 nike

我目前在 mysql 中有 2 个表; 评论comment_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 查询)获得按最佳评分排序的评论;意思是按每条评论的评分总和排序。

例子:

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

这些将出现的顺序将是:

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

最佳答案

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

关于php - MySQL按另一个表的总和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25046232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com