How to get row count of two tables in different databases in a single query?


For this, you can use aggregate function COUNT(*). Let us first create a table in let’s say database “web” −

mysql> create table DemoTable1
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable1 values(20);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-------+
| Value |
+-------+
|    10 |
|    20 |
+-------+
2 rows in set (0.00 sec)

Following is the query to create second table in another database with the name “test” −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(100);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable2 values(200);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-------+
| Value |
+-------+
|   100 |
|   200 |
+-------+
2 rows in set (0.00 sec)

Following is the query to get row count of 2 tables in different databases in a single query −

mysql> select
   -> (
   -> select count(*) from web.DemoTable1) AS Table1Count,
   -> (select count(*) from test.DemoTable2) AS Table2Count;

This will produce the following output −

+---------------+---------------+
| Table1Count   | Table2Count   |
+---------------+---------------+
|             2 |             2 |
+---------------+---------------+
1 row in set (0.06 sec)
raja
Published on 11-Jul-2019 11:27:31
Advertisements