为此,将聚合函数COUNT()
与GROUP BY一起使用。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Value) values(976); mysql> insert into DemoTable(Value) values(67); mysql> insert into DemoTable(Value) values(67); mysql> insert into DemoTable(Value) values(1); mysql> insert into DemoTable(Value) values(90); mysql> insert into DemoTable(Value) values(1); mysql> insert into DemoTable(Value) values(67); mysql> insert into DemoTable(Value) values(976); mysql> insert into DemoTable(Value) values(90); mysql> insert into DemoTable(Value) values(1); mysql> insert into DemoTable(Value) values(10);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
+----+-------+ | Id | Value | +----+-------+ | 1 | 976 | | 2 | 67 | | 3 | 67 | | 4 | 1 | | 5 | 90 | | 6 | 1 | | 7 | 67 | | 8 | 976 | | 9 | 90 | | 10 | 1 | | 11 | 10 | +----+-------+ 11 rows in set (0.00 sec)
以下是查询以获取MySQL中最频繁出现的值的计数-
mysql> select Value,COUNT(Value) AS ValueFrequency from DemoTable group by Value order by ValueFrequency DESC;
输出结果
+-------+----------------+ | Value | ValueFrequency | +-------+----------------+ | 67 | 3 | | 1 | 3 | | 90 | 2 | | 976 | 2 | | 10 | 1 | +-------+----------------+ 5 rows in set (0.09 sec)