数据库
首页 > 数据库> > 关于MySQL多表联查并求和计算?

关于MySQL多表联查并求和计算?

作者:互联网

是这样的一个情况 这里有三张表 分别是用户user,订单 trade ,和资金记录 user_money_record
现在要根据用户来统计他们的订单总金额和账户余额以及充值总金额

user表
id realname money
1 张xx 100
2 王xx 500
3 李xx 1500

trade
id uid realmoney
1 2 5000
2 1 1000
3 2 5000
4 3 10000
5 1 3500

user_money_record
id uid money
1 2 5000
2 1 5000
3 2 2000
4 2 3000
5 3 5000
6 3 5000

表结构及数据如上
求统计他们的订单总金额和账户余额以及充值总金额

select u.name,t.realmoney,umr.money from user u
left join 
(select uid,sum(realmoney) as realmoney from trade group by uid) t on t.uid = u.id
left join
(select uid,sum(money) as money from user_money_record group by uid) umr on umr.uid = uid

标签:realmoney,5000,多表,uid,money,user,MySQL,联查,id
来源: https://blog.csdn.net/qq_15907907/article/details/116984613