how to get SUM from two different tables that are linked to third one

后端 未结 6 1361
故里飘歌
故里飘歌 2021-01-24 02:41

ok the problem is that I have to sum two sums from two tables that are linked

first table points:

id | user_id | point | hit
1  | 1       |     4 | yes
2         


        
6条回答
  •  粉色の甜心
    2021-01-24 02:56

    If you want total earnings per user, you should probably start by identifying which users you want earnings for. The most sensible option is probably to use the users table itself as the basis.

    SELECT user_id,
           (SELECT SUM(point)
              FROM points
             WHERE user_id = u.user_id
           )
           +
           (SELECT SUM(earning)
              FROM earnings
             WHERE user_id = u.user_id
               AND p.hit IN ('yes', 'no')
           ) AS bb
      FROM users
    

    This approach has the added benefit of reporting on users who had no points and/or earnings.

提交回复
热议问题