带有双SUM语句的SQL查询

时间:2015-05-06 21:06:24

标签: php mysql database

有两张桌子: - 话题 - 帖子

帖子有“评分”功能:

topic 1, post 1, rating 2
topic 1, post 1, rating 2
topic 1, post 2, rating 1

主题有“观看”功能:

topic 1, views 5
topic 1, views 3

我希望获得所有主题的帖子评分总和以及所有主题的总结视图。 我的 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`

1 个答案:

答案 0 :(得分:1)

看看这是否有帮助。此方法在派生表上使用LEFT JOIN,并在该派生表中执行SUMMING for topics表。无论主题表中是否存在相应的条目,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