计数 MySQL 中的公共元素?


要计数公共元素,请使用 COUNT() 和 GROUP BY。让我们首先创建一个表 -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Number int
   );
Query OK, 0 rows affected (0.20 sec)

使用插入命令将一些记录插入表 -

mysql> insert into DemoTable(Number) values(10);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Number) values(20);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Number) values(20);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Number) values(30);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Number) values(10);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(Number) values(10);
Query OK, 1 row affected (0.04 sec)

使用 select 语句显示表中的所有记录 -

mysql> select *from DemoTable;

这将产生以下输出 -

+----+--------+
| Id | Number |
+----+--------+
| 1  | 10     |
| 2  | 20     |
| 3  | 20     |
| 4  | 30     |
| 5  | 10     |
| 6  | 10     |
+----+--------+
6 rows in set (0.00 sec)

以下是计算公共元素的查询 -

mysql> select Number,count(Number) as CommonElement from DemoTable group by Number;

这将产生以下输出 -

+--------+---------------+
| Number | CommonElement |
+--------+---------------+
| 10     | 3             |
| 20     | 2             |
| 30     | 1             |
+--------+---------------+
3 rows in set (0.00 sec)

更新日期: 30-7 月-2019

363 次浏览

开启您的 职业

通过完成课程获得认证

开始
广告