2017-03-12 146 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