
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Rows from Multiple Tables in MySQL
To count rows from multiple tables in MySQL, the syntax is as follows −
Select (select count(*) from yourTableName1) as anyAliasName1, (select count(*) from yourTableName2) as anyAliasName2 from dual;
Let us first create a table −
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY -> ); Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(),(),(),(),(),(); Query OK, 6 rows affected (0.24 sec) Records: 6 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1;
This will produce the following output −
+----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +----+ 6 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2 -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values('Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable2 values('David'); Query OK, 1 row affected (0.31 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2;
This will produce the following output −
+-------+ | Name | +-------+ | Chris | | David | +-------+ 2 rows in set (0.00 sec)
Following is the query to count rows from multiple tables −
mysql> select -> (select count(*) from DemoTable1) as FirstTable1Count, -> (select count(*) from DemoTable2) as SecondTable2Count -> from dual;
This will produce the following output −
+---------------------+----------------------+ | FirstTable1Count | SecondTable2Count | +---------------------+----------------------+ | 6 | 2 | +---------------------+----------------------+ 1 row in set (0.00 sec)
Advertisements