2015-04-05 59 views
0

這是tbl_user:SUM MySQL表的多個列的

----------------- 
ID | Username 
----------------- 
1  user one 
2  user two 

這是tbl_x1:

------------------------- 
ID | User_id | Sum 
------------------------- 
1  1   10 
2  1   20 
3  2   30 

這是tbl_x2:

------------------------- 
ID | User_id | Sum 
------------------------- 
1  1   10 
2  1   20 
3  1   30 

這是tbl_y:

------------------------- 
ID | User_id | Days 
------------------------- 
1  1   10 

我想選擇sum(x1.sum + x2.sum)和sum(y.Days)。
換句話說,我想以下結果:

------------------------------------- 
ID | Username | Sum | Days 
------------------------------------- 
1  user one  90  10 
2  user two  30  0 

我這個代碼的嘗試:

select u.id as ID, u.username as Username, sum(y.days) as Days,(ifnull(sum(x1.sum), 0) + ifnull(sum(x2.sum), 0)) as Sum from tbl_user u left join tbl_x1 x1 on u.id = x1.user_id left join tbl_x2 g on u.id = x2.user_id left join tbl_y y on u.id = y.user_id group by u.id 

,但我得到錯誤的結果。

+0

而問題是什麼?你卡在哪裏?你有錯誤嗎? – 2015-04-05 12:58:26

+0

該查詢不起作用。 – Garme 2015-04-05 13:17:58

回答

1

問題是,對於給定的user_idjoin操作會使行倍增。通過乘以行(稱爲「笛卡爾乘積」),您會得到錯誤的總和。

解決的辦法是做聚合之前做連接:

select u.id as ID, u.username as Username, y.days, 
     coalesce(x1.sum, 0) + coalesce(x2.sum, 0)) as Sum 
from tbl_user u left join 
    (select x1.user_id, sum(x1.sum) as sum 
     from tbl_x1 x1 
     group by x1.user_id 
    ) x1 
    on u.id = x1.user_id left join 
    (select x2.user_id, sum(x.sum) as sum 
     from tbl_x2 x2 
     group by x2.user_id 
    ) x2 
    on u.id = x2.user_id left join 
    (select y.user_id, sum(y2.days) as days 
     from tbl_y y 
     group by y.user_id 
    ) y 
    on u.id = y.user_id; 
+0

在加入多個表的情況下,通過將總和除以重複值的重複次數,可以得到與簡單連接相同的結果!? – jfun 2015-04-05 13:40:23

+0

現在,我想寫一個聲明。例如:(WHERE sum - days <10)但錯誤。正確的方法是什麼? – Garme 2015-04-05 15:53:11

+0

@Farhęg。 。 。這可能適用於一個連接,但有多個連接會變得相當複雜。 – 2015-04-05 20:52:53