MySQL query to sum the values of similar columns from two different tables for a particular ID


Let’s say we have two tables and both of them have two columns PlayerId and PlayerScore. We need to add the PlayerScore from both these tables, but only for a particular PlayerId.

For this, you can use UNION. Let us first create a table −

mysql> create table DemoTable1(PlayerId int,PlayerScore int);
Query OK, 0 rows affected (9.84 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(1000,87);
Query OK, 1 row affected (3.12 sec)
mysql> insert into DemoTable1 values(1000,65);
Query OK, 1 row affected (1.29 sec)
mysql> insert into DemoTable1 values(1001,10);
Query OK, 1 row affected (1.76 sec)
mysql> insert into DemoTable1 values(1000,45);
Query OK, 1 row affected (2.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+----------+-------------+
| PlayerId | PlayerScore |
+----------+-------------+
| 1000     | 87          |
| 1000     | 65          |
| 1001     | 10          |
| 1000     | 45          |
+----------+-------------+
4 rows in set (0.00 sec)

Following is the query to create second table −

mysql> create table DemoTable2(PlayerId int,PlayerScore int);
Query OK, 0 rows affected (11.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(1000,67);
Query OK, 1 row affected (0.71 sec)
mysql> insert into DemoTable2 values(1001,58);
Query OK, 1 row affected (1.08 sec)
mysql> insert into DemoTable2 values(1000,32);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+----------+-------------+
| PlayerId | PlayerScore |
+----------+-------------+
| 1000     | 67          |
| 1001     | 58          |
| 1000     | 32          |
+----------+-------------+
3 rows in set (0.00 sec)

Following is the query to sum a column in one table with column in another table. Here, we are adding PlayerScore for PlayerId 1000 −

mysql> select sum(firstSum) from
   (select Sum(PlayerScore) firstSum from DemoTable1 where PlayerId=1000 union
   select Sum(PlayerScore) firstSum from DemoTable2 where PlayerId=1000) tbl;

This will produce the following output −

+---------------+
| sum(firstSum) |
+---------------+
|           296 |
+---------------+
1 row in set (0.02 sec)

Updated on: 22-Aug-2019

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements