统计 MySQL 表中记录出现的次数并在新列中显示结果?


为此,请与 GROUP BY 子句一起使用 COUNT(*)。我们首先创建一个表 -

mysql> create table DemoTable1942
   (
   Value int
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1942;

这将产生以下输出 -

+-------+
| Value |
+-------+
|     1 |
|     2 |
|     3 |
|     2 |
|     3 |
|     3 |
|     1 |
+-------+
7 rows in set (0.00 sec)

此处是用于统计出现次数的查询

mysql> select Value, count(*) from DemoTable1942
   group by Value;

这将产生以下输出 -

+-------+----------+
| Value | count(*) |
+-------+----------+
|     1 |        2 |
|     2 |        2 |
|     3 |        3 |
+-------+----------+
3 rows in set (0.00 sec)

更新于:31-12-2019

2K+ 次浏览

职业 起点

完成课程并获得认证

开始
广告