php - 使用双 SUM 语句的 SQL 查询

标签 php mysql database

有 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/

相关文章:

更改数据类型时MySQL锁等待超时

php - $_POST 值在 SSL 打开后消失

mysql - MariaDB:选择 val_1、max(value_2)、按 value_3 分组

mysql - 选择嵌套的 AND OR。如何?

mysql - 如何从匹配两个相似列的表中选择不同的 ID?

java - MySQL安装帮助

php - 最大附件大小邮件服务

php - date_create_from_format 等效于 PHP 5.2(或更低版本)

php - Symfony2 - 呈现引用为父类(super class)实例的对象的子类属性

sql - 插入/更新时将数据类型 varchar 转换为数字时出错