消息关闭
    暂无新消息!

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

问题作者 : 黑人2017-05-10发布

是这样的一个情况 这里有三张表 分别是用户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

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

谢谢!


3个回答

︿ 0

如果user表的信息是最完整的,应该是这样的:

SELECT *
FROM (SELECT id, sum(money) FROM user GROUP BY id) t1 
  LEFT JOIN (SELECT id, sum(realmoney) FROM trade GROUP BY id) t2 ON t1.id = t2.id
  LEFT JOIN (SELECT id, sum(money) FROM user_money_record GROUP BY id) t3 ON t1.id = t3.id
︿ 0

我猜想你可能是要这样的

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