To count values from separate tables, the syntax is as follows −
Select ( select count(yourColumnName) from yourTableName1) as anyAliasName1, ( select count(yourColumnName) from yourTableName2) as anyAliasName2;
Let us first create a table −
mysql> create table DemoTable1 -> ( -> Id int -> ); Query OK, 0 rows affected (1.06 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(1); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1 values(NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1 values(2); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable1 values(3); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1;
This will produce the following output −
+------+ | Id | +------+ | 1 | | NULL | | 2 | | 3 | +------+ 4 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2 -> ( -> Id int -> ); Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(10); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable2 values(NULL); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable2 values(NULL); Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2;
This will produce the following output −
+------+ | Id | +------+ | 10 | | NULL | | NULL | +------+ 3 rows in set (0.00 sec)
Here is the query to get count from separate tables −
mysql> select -> ( -> select count(Id) from DemoTable1) as CountFirstTableId, -> ( -> select count(Id) from DemoTable2) as CountSecondTableId -> ;
This will produce the following output −
+-------------------+--------------------+ | CountFirstTableId | CountSecondTableId | +-------------------+--------------------+ | 3 | 1 | +-------------------+--------------------+ 1 row in set (0.00 sec)