2017-03-12 92 views
0

我需要它有4个表来进行选择,并通过对每个userID在表predsexactreward值相加得到的前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 
+0

您有问题要问?我建议你在FROM子句中永远不要使用逗号。 –

回答

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

+0

我调整了一下你的代码,并得到了我想要的结果。另外,我不得不在最后用userID进行分组。谢谢。 – user1542894

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返回的记录量,这不应该是一个显着的性能影响

+0

实际上我并不需要它们,我只需要它们的总和。我将如何去加入他们? – user1542894

+0

这取决于你的表格布局。但是,如果你只是进行汇总,我的解决方案应该工作 – Psi