A single query to get the sum of count from different tables in MySQL?



To get the sum of count from different tables, use UNION ALL. Let us first create a table −

mysql> create table DemoTable1 -> ( -> Id int, -> Name varchar(30) -> ); Query OK, 0 rows affected (1.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(10,'Chris Brown'); Query OK, 1 row affected (0.83 sec) mysql> insert into DemoTable1 values(20,'David Miller'); Query OK, 1 row affected (0.50 sec) mysql> insert into DemoTable1 values(30,'John Adam'); Query OK, 1 row affected (0.83 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

Output

+------+--------------+ | Id   | Name         | +------+--------------+ | 10   | Chris Brown | | 20   | David Miller | | 30   | John Adam    | +------+--------------+ 3 rows in set (0.00 sec)

Following is the query to create second table −

mysql> create table DemoTable2 -> ( -> Amount int -> ); Query OK, 0 rows affected (1.17 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(100); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable2 values(200); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2 values(300); Query OK, 1 row affected (0.54 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

Output

+--------+ | Amount | +--------+ | 100    | | 200    | | 300    | +--------+ 3 rows in set (0.00 sec)

Here is how to get sum of count from different tables in a single query −

mysql> select sum(AllCount) AS Total_Count -> from -> ( -> (select count(*) AS AllCount from DemoTable1) -> union all -> (select count(*) AS AllCount from DemoTable2) -> )t;

Output

+-------------+ | Total_Count | +-------------+ | 6           | +-------------+ 1 row in set (0.03 sec)
Updated on: 2019-11-04T10:42:49+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements