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.
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
Explanation
First of all we need to get a list of all the user ids that are present in either
table1ortable2so we can use this list as the dataset to do aLEFT OUTER JOINfrom. Any approach that starts the join fromtable1ortable2is 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
useridsresultset through the subselect weLEFT JOINboth 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 ofNULLfor that user (becauseNULL + numbergivesNULL), so we useCOALESCEto convert anyNULLto0.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.