mysql - Summing values over multiple, non-related tables? -
i have 3 tables: users, sales , points.
each user has multiple sales , multiple points.
sales have column "value" , points have column "score", so
users = | user_id | name | sales = | sale_id | user_id | value | points = | point_id | user_id | score |
now want show listing of users sums of sales , points so
user_id | sum(sales.value) | sum(points.value) 1 | 500 | 200 2 | 213 | 132 3 . . .
is possible achieve in 1 query, without using subqueries?
or best, simpliest approach? i'm trying simplify as possible because have lots of information related users have show in manner.
i tried using left joins when join 2 one-to-many tables in 1 query, sum becomes messed because of repeated rows. tried grouping data think i'm lost.
the "right" approach in sql summarize tables before joining them:
select u.user_id, sumvalue, sumscore users u left outer join (select user_id, sum(value) sumvalue sales group user_id ) s on u.user_id = s.user_id left outer join (select user_id, sum(score) sumscore points group user_id ) p on u.user_id = p.user_id;
Comments
Post a Comment