Peeyush
Peeyush

Reputation: 4828

How to sum data of two different columns of two different tables?

i have two tables i my database in which i have two columns in each table one is for userid & one is for showing some numeric data.

I just want to add the value of the numeric column but the issue is that it's not compulsory that both the table have same used id.

I will try to explain it using example:

table1

userid  score1

  1       200
  2       300


table2

userid  score2

  1       400

so now what i want to do is to sum the score form these two tables as per the user id and show it in a new table like this:

userid  score_sum

  1       600
  2       300

if i simply use

Select sum(table1.score1+table2.score2) 
FROM table1 JOIN table2 ON table1.id=table2.id

then it will only show the sum for userid 1 because userid 2 is not present in the second table.So please suggest me how to solve this issue.

Upvotes: 2

Views: 8864

Answers (3)

Chris Moutray
Chris Moutray

Reputation: 18349

Not sure there is a need for joins, just need to union (all) score tables and group & sum in outer query

SELECT userid, SUM(score)
FROM ( 
    SELECT userid, score1 as score FROM table1 
    UNION ALL SELECT userid, score2 as score FROM table2
) t 
GROUP BY t.userid 

Upvotes: 4

Jon
Jon

Reputation: 437336

Normally you would solve this problem by doing a full outer join, but MySql does not support such joins so it needs to be faked.

The query

SELECT SUM(COALESCE(table1.score1,0) + COALESCE(table2.score2,0))
FROM (
    SELECT DISTINCT(id) FROM (
        SELECT userid FROM table1 UNION SELECT userid FROM table2
    ) tmp
) userids
LEFT JOIN table2 ON table2.userid = userids.userid
LEFT JOIN table1 ON table1.userid = userids.userid
GROUP BY table1.userid

Explanation

First of all we need to get a list of all the user ids that are present in either table1 or table2 so we can use this list as the dataset to do a LEFT OUTER JOIN from. Any approach that starts the join from table1 or table2 is not going to cut it because if the selected table does not include some user id X then that user will not appear at all in the final results.

Having created the userids resultset through the subselect we LEFT JOIN both interesting tables to get the scores for each user. If a user is not present in both tables then we 're going to have a score of NULL for that user (because NULL + number gives NULL), so we use COALESCE to convert any NULL to 0.

I should note that this query will work correctly irrespective of which user is included (or not) in which table, or of the order that the tables appear in the query.

Upvotes: 4

Voislav Sauca
Voislav Sauca

Reputation: 3075

SELECT SUM(table1.score1 + IS NULL(table2.score2) 
FROM table1 
LEFT JOIN table2 
ON table1=table1.id

Upvotes: 0

Related Questions