有 2 个表: - 主题 - 帖子
帖子具有“评分”功能:
topic 1, post 1, rating 2
topic 1, post 1, rating 2
topic 1, post 2, rating 1
主题具有“ View ”功能:
topic 1, views 5
topic 1, views 3
我想获得所有主题的帖子评分总和以及所有主题的总 View 。 我的坏 SQL:
SELECT
forum_id,
topic_id,
SUM(t1.rating),
SUM(t2.views)
FROM
posts t1
LEFT JOIN
topics t2 ON t1.topic_id = t2.topic_id
GROUP BY
t1.topic_id
它返回的值不正确,我认为 - 通过加入原因 - 他们需要分组 2 次。
我可以做什么来解决?
阅读回复后添加:
SELECT
t1.`forum_id`,
t1.`topic_id`,
SUM(t1.`rating`) AS rating,
t3.`views` AS views
FROM
`forum_ratings_posts` t1
LEFT JOIN (
SELECT
SUM(t2.`views`) AS views,
t2.`topic_id`
FROM
`forum_ratings_topics` t2
GROUP BY
t2.`topic_id`
) t3 ON t1.`topic_id` = t3.`topic_id`
GROUP BY
t1.`topic_id`
最佳答案
看看这是否有帮助。此方法在派生表上使用LEFT JOIN
,并对该派生表中的主题表进行求和。 LEFT JOIN
将确保您拥有 posts 表中的条目,无论主题表中是否存在相应条目。如果您需要更多信息,请告诉我。
SELECT
t1.forum_id,
t1.topic_id,
SUM(t1.rating),
temp.t2_sum
FROM
posts t1
LEFT JOIN
(SELECT SUM(views) AS t2_sum, topic_id FROM topics GROUP BY
topic_id) AS temp
ON t1.topic_id = temp.topic_id
GROUP BY
t1.topic_id
关于php - 使用双 SUM 语句的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30087510/