Home  >  Q&A  >  body text

关于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

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

谢谢!

PHP中文网PHP中文网2763 days ago730

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 16:10:29

    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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 16:10:29

    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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 16:10:29

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

    reply
    0
  • Cancelreply