【问题标题】:Select two tables and Sum column value选择两个表并求和列值
【发布时间】:2017-03-12 13:31:07
【问题描述】:

我需要执行一个包含 4 个表的 Select,并通过将表 predsexact 中每个 userIDreward 值相加来获得前 5 个分数:

 -----table------columns-----

 1. tbl_users - `userID`
 2. matches   - `id` (there are other columns I use for the clauses)
 3. preds     - `uid` (same as `userID`)
                `mid` (same as `matches.id`)
                `reward` (this is the column I need to sum up)
 4. exact     - same structure as `preds`

这是我一直在想的:

SELECT ( 
      select sum(preds.reward) FROM preds, matches, tbl_users WHERE ...some clauses...              
) a,
( 
      select sum(exact.reward) FROM exact, matches, tbl_users WHERE ...some clauses...     
) b, 
      ...here I need to sum(a+b) as total..., 
      tbl_users.userID
FROM
      tbl_users
GROUP BY userID 
ORDER BY total DESC LIMIT 5

【问题讨论】:

  • 您有问题吗?我建议您从不FROM 子句中使用逗号。

标签: mysql sql sum subquery


【解决方案1】:

我认为这个查询更典型的方法是:

SELECT u.uid,
       ((select sum(p.reward) 
         from preds p
         where p.uid = u.uid
        ) +
        (select sum(e.reward) 
         from exact e
         where e.uid = u.uid
        )
       ) total
from tbl_users u join
     matches m
     on . . .
where . . .
order by total desc
limit 5;

这限制了查询的复杂性。根据where 子句的性质,使用相关子查询可以大大提高性能。

注意:如果用户可能从一个或两个表中丢失,您需要考虑到子查询可能返回 NULL

【讨论】:

  • 我稍微调整了你的代码,得到了我想要的结果。最后我还必须按用户 ID 分组。谢谢。
【解决方案2】:

好吧,如果您真的需要这些子查询而不是加入它们,您唯一的解决方案似乎是另一个子查询:

SELECT combined.a, combined.b, combined.a + combined.b as sum, combined.userID
FROM (
    SELECT ( 
          select sum(preds.reward) FROM preds, matches, tbl_users WHERE ...some clauses...              
    ) a,
    ( 
          select sum(exact.reward) FROM exact, matches, tbl_users WHERE ...some clauses...     
    ) b, 
          tbl_users.userID userID
    FROM
      tbl_users
    GROUP BY userID 
    ORDER BY total DESC LIMIT 5
) as combined

将内部查询返回的记录数限制为 5 条后,这应该不会对性能产生显着影响

【讨论】:

  • 我实际上不需要它们,我只需要总和。我将如何加入他们?
  • 这取决于您的表格布局。但是,如果您只是进行聚合,我的解决方案应该可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
相关资源
最近更新 更多