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

后端 未结 6 1369
故里飘歌
故里飘歌 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 03:12

    The problem of you query is that with the join on the user field, you will get multiple rows... You have to do the sums and then put the data together, unless you have a 1-1 relationship between points and earnings tables (like the id)

    A solution could be to create the table with the two sums and join them to get your data

    select COALESCE(P.user_id, E.user_id), points, earnings, 
    

    sum(COALESCE(points,0) + COALESCE(earnings,0)) from

    (select user_id, sum(point) as points from points 
    

    where (p.hit = "yes" OR p.hit = "no") group by user_id) as P

    full outer join
    
    (select user_id, sum(earning) as earnings from earnings group by user_id) as E
    on P.user_id = E.user_id
    
    group by COALESCE(P.user_id, E.user_id)
    

    I used FULL OUTER JOIN and coalesce to be sure that data are provided eve if one of the table is missing. If this is not necessary, you could alter your join condition (to a LEFT OUTER JOIN if, for example, you need data only whenere there is at least one valid point)

提交回复
热议问题