这是tbl_user:
-----------------
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 :(得分:1)
问题是join
操作会乘以给定user_id
的行。通过乘以行(称为“笛卡尔积”),您得到的是错误的总和。
解决方案是在进行连接之前进行聚合:
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;