MySQL部门用户人员求和_MySQL的加入和求和

bd96500e110b49cbb3cd949968f18be7.png

Please look to this picture

i want to get

sum of money in table come

sum of money in table leave

inner join emp using id

Thats my query

SELECT uid,SUM(money) FROM come

INNER JOIN emp ON(come.uid = emp.id)

WHERE emp.statue=1

GROUP BY come.uid

UNION

SELECT uid,SUM(money) FROM `leave`

INNER JOIN emp ON ( leave.uid = emp.id )

GROUP BY leave.uid

and the result was this image

解决方案

Another way to do it (not tested, so let me know if it blows up):

SELECT emp.id, IF(emp.statue=1, c.sumCome, 0) AS sumCome, l.sumLeave

FROM emp

LEFT JOIN (SELECT uid, SUM(money) AS sumCome

FROM come

GROUP BY uid

) c ON emp.id = c.uid

LEFT JOIN (SELECT uid, SUM(money) AS sumLeave

FROM leave

GROUP BY uid

) l ON emp.id = l.uid

I don't know which'll be faster compared to Kevin's. You might want to explain them both and see.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值