记一次复杂查询

项目中有一个需求,查出用户取出,充值次数,金额,用户名,金币的总量和每局游戏的盈亏等做一个统计,而他们分布在个表中,分别是用户表,用户取出表,用户充值表,每局游戏表中。

  1. 首先想到的就是要分组查询,group by user.userId.
  2. 因为有的用户有充值记录但不一定有取出记录,所以需要外连接查询。
  3. 由于有些数据比如每局游戏的盈亏是表中没有的,需要用到子查询,再连接到主查询上。

最后sql

select members.user_name as userName,
        count(deposit_id) as depositCount,
        count(withdraw_id) as withdrawCount,
        sum(deposit_amount) as depositSum,
        sum(withdraw_amount) as withdrawSum,
        profitAndLosses,
        valiwin.validwin
        from
        members
        left join member_deposit on member_deposit.user_id=members.user_id
        LEFT JOIN member_withdraw on member_withdraw.user_id=members.user_id
        left join (select members.user_id as validwinUserId,
        members.user_name as userName,sum(win_money) as validwin
        from members right join api_win
        on api_win.user_id =members.user_id
        where settlement_status=1
        GROUP BY members.user_id) as valiwin on members.user_id=valiwin.validwinUserId
        left join (select members.user_id as profitAndLossUserId,
        members.user_name as userName,sum(profitAndLoss) as profitAndLosses
        from members right join api_win
        on api_win.user_id =members.user_id
        GROUP BY members.user_id) profitAndLoss on members.user_id=profitAndLoss.profitAndLossUserId
        group by `members`.user_id
posted @ 2019-03-23 22:46  陈跃进同志  阅读(96)  评论(0编辑  收藏  举报