选择两个表和Sum列值

时间:2017-03-12 13:31:07

标签: mysql sql sum subquery

我需要在其中执行包含4个表格的选择,并通过对每个reward的表格predsexact中的userID值求和来获得前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

2 个答案:

答案 0 :(得分:1)

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

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之后,这不会对性能产生显着影响

答案 1 :(得分: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;

这限制了查询的复杂性。根据{{​​1}}子句的性质,使用相关子查询可以获得很大的性能提升。

注意:如果一个或两个表中的用户可能丢失,则需要考虑子查询可能返回where