- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements