How can I sum columns across multiple tables in MySQL?

MySQLMySQLi Database

To sum columns across multiple tables, use UNION ALL. To understand the concept, let us create first table. The query to create first table is as follows

mysql> create table Products1
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ProductName varchar(20),
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.50 sec)

Insert some records in the first table using insert command. The query is as follows −

mysql> insert into Products1(ProductName,ProductPrice) values('Product-1',100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into Products1(ProductName,ProductPrice) values('Product-2',200);
Query OK, 1 row affected (0.34 sec)
mysql> insert into Products1(ProductName,ProductPrice) values('Product-3',700);
Query OK, 1 row affected (0.15 sec)

Now you can display all records from the first table using select statement. The query is as follows −

mysql> select *from Products1;

The following is the output

+-----------+-------------+--------------+
| ProductId | ProductName | ProductPrice |
+-----------+-------------+--------------+
|         1 | Product-1   |          100 |
|         2 | Product-2   |          200 |
|         3 | Product-3   |          700 |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)

Let us create second table. The query to create it is as follows

mysql> create table Products2
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ProductName varchar(20),
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the second table using insert command. The query is as follows −

mysql> insert into Products2(ProductName,ProductPrice) values('Product-1',500);
Query OK, 1 row affected (0.24 sec)
mysql> insert into Products2(ProductName,ProductPrice) values('Product-4',100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into Products2(ProductName,ProductPrice) values('Product-5',400);
Query OK, 1 row affected (0.10 sec)

Now you can display all records from the second table using select statement. The query is as follows −

mysql> select *from Products2;

The following is the output

+-----------+-------------+--------------+
| ProductId | ProductName | ProductPrice |
+-----------+-------------+--------------+
|         1 | Product-1   |          500 |
|         2 | Product-4   |          100 |
|         3 | Product-5   |          400 |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)

Here is the query to sum columns across multiple tables in MySQL

mysql> SELECT SUM(tbl.ProductPrice) AS TotalPrice
   -> FROM (SELECT ProductPrice FROM Products1
   -> UNION ALL
   -> SELECT ProductPrice FROM Products2) tbl;

The following is the output

+------------+
| TotalPrice |
+------------+
|       2000 |
+------------+
1 row in set (0.04 sec)
raja
Published on 01-Apr-2019 09:47:31
Advertisements