How to count rows from two tables in a single MySQL query?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1
(
   Name varchar(40)
);
Query OK, 0 rows affected (0.81 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.48 sec)
mysql> insert into DemoTable1 values('Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1 values('Mike');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+--------+
| Name   |
+--------+
| Chris  |
| Robert |
| Mike   |
+--------+
3 rows in set (0.00 sec)

Following is the query to create the second table −

mysql> create table DemoTable2
(
   Score int
);
Query OK, 0 rows affected (1.16 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(86);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable2 values(98);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable2 values(75);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-------+
| Score |
+-------+
| 86    |
| 98    |
| 75    |
+-------+
3 rows in set (0.00 sec)

Following is the query to count rows from two tables in one query −

mysql> select
   (select count(*) from DemoTable1) AS FirstTableCount,
   (select count(*) from DemoTable2) AS SecondTableCount
   from dual;

This will produce the following output −

+-----------------+------------------+
| FirstTableCount | SecondTableCount |
+-----------------+------------------+
| 3               | 3                |
+-----------------+------------------+
1 row in set (0.00 sec)
raja
Published on 04-Oct-2019 08:32:53
Advertisements