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

元气小坏坏 提交于 2020-01-04 09:18:08

问题


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.


回答1:


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.




回答2:


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 



回答3:


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


来源:https://stackoverflow.com/questions/10206763/how-to-sum-data-of-two-different-columns-of-two-different-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!