在MySQL中计算两个表中的字符串数量并给出组合数量?
要进行计数,请使用MySQL COUNT(*)。但是,通过使用UNION ALL,您可以获得组合字符串的计数。让我们首先创建一个表 –
mysql> create table DemoTable1
(
Name varchar(20)
);
Query OK, 0 rows affected (0.49 sec)
使用insert命令向表中插入一些记录。我们将在第一个表中插入字符串值 –
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)
使用select语句显示来自表的所有记录 –
mysql> select *from DemoTable1;
这将产生以下输出 –
+--------+
| Name |
+--------+
| Chris |
| Robert |
| Mike |
| Robert |
+--------+
4 rows in set (0.00 sec)
以下是创建第二个表的查询。我们也在第二个表中插入字符串值 –
mysql> create table DemoTable2
(
Name varchar(40)
);
Query OK, 0 rows affected (0.43 sec)
使用insert命令向表中插入一些记录 –
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)
使用select语句显示来自表的所有记录 –
mysql> select *from DemoTable2;
这将产生以下输出 –
+--------+
| Name |
+--------+
| Robert |
| Chris |
| Robert |
| David |
+--------+
4 rows in set (0.00 sec)
以下是使用COUNT(*)和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;
这将产生以下输出。组合计数显示在新列“Total_Count”中 –
+--------+-------------+
| Name | Total_Count |
+--------+-------------+
| Chris | 2 |
| Robert | 4 |
| Mike | 1 |
| David | 1 |
+--------+-------------+
4 rows in set (0.00 sec)
阅读更多:MySQL 教程