1. 程式人生 > >記一次復雜查詢

記一次復雜查詢

where pro 一次 sse ember money pre group by sta

項目中有一個需求,查出用戶取出,充值次數,金額,用戶名,金幣的總量和每局遊戲的盈虧等做一個統計,而他們分布在個表中,分別是用戶表,用戶取出表,用戶充值表,每局遊戲表中。

  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

記一次復雜查詢