关于MySQL多表联查并求和计算?
PHP中文网
PHP中文网 2017-04-17 16:08:29
0
3
744

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

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

谢谢!

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
刘奇

I guess you may want to do this

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
Peter_Zhu

If the information in the user table is the most complete, it should look like this:

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
左手右手慢动作

How to deal with this situation if the amount of data is too large

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template