计算评论数并从mysql获得平均评分

时间:2018-10-31 11:15:17

标签: mysql sql

我只是不知道如何从mysql数据库中获得平均评分和计数评论。

我有3个表(活动,评分,评论),活动包含“活动”的主要数据,评分包含评分和评论-当然是评分。

activity_table

id | title |short_desc | long_desc | address | lat | long |last_updated

rating_table

id | activityid | userid | rating

comment_table

id | activityid | userid | rating

我现在正在尝试在一个查询中获取活动数据,comment_counts和average_rating。

SELECT activity.*, AVG(rating.rating) as average_rating, count(comments.activityid) as total_comments
FROM activity LEFT JOIN
     rating
     ON activity.aid = rating.activityid LEFT JOIN
     comments
     ON activity.aid = comments.activityid
GROUP BY activity.aid 

...不做这项工作。它给了我正确的average_rating,但错误的注释量。

有什么想法吗? 非常感谢!

1 个答案:

答案 0 :(得分:0)

您正在沿着两个不同维度进行汇总。联接生成的笛卡尔乘积会影响聚合。

因此,您应该在join s之前进行汇总:

SELECT a.*, r.average_rating, COALESCE(c.total_comments, 0) as total_comments
FROM activity a LEFT JOIN
     (SELECT r.activityid, AVG(r.rating) as average_rating
      FROM rating r
      GROUP BY r.activityid
     ) r
     ON a.aid = r.activityid LEFT JOIN
     (SELECT c.activityid, COUNT(*) as total_comments
      FROM comments c
      GROUP BY c.activityid
     ) c
     ON a.aid = c.activityid;

请注意,不再需要外部GROUP BY