Count from two tables and give combined count of string in MySQL?

MySQLMySQLi Database

To count, use the MySQL COUNT(*). However, with UNION ALL you would be able to get a combined count of string. Let us first create a table −

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

Insert some records in the table using insert command. We are inserting string values in the first table −

mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values('Robert');
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   |
| Robert |
+--------+
4 rows in set (0.00 sec)

Following is the query to create the second table. We are inserting string values in the second table as well −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values('Robert');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable2 values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable2 values('Robert');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable2 values('David');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+--------+
| Name   |
+--------+
| Robert |
| Chris  |
| Robert |
| David  |
+--------+
4 rows in set (0.00 sec)

Following is the query to get the combined count of string values from both the tables using COUNT(*) and UNION ALL −

mysql> select tbl.Name,count(*) as Total_Count from
(
   select Name from DemoTable1
   UNION ALL
   select Name from DemoTable2
)tbl
group by tbl.Name;

This will produce the following output. The combined count is displayed in a new column “Total_Count” −

+--------+-------------+
| Name   | Total_Count |
+--------+-------------+
| Chris  |           2 |
| Robert |           4 |
| Mike   |           1 |
| David  |           1 |
+--------+-------------+
4 rows in set (0.00 sec)
raja
Published on 04-Oct-2019 07:37:26
Advertisements