在 MySQL 中获得出现最频繁的值的计数?
对此,使用聚合函数 COUNT() 和 GROUP BY。我们首先创建一个表,
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int ); Query OK, 0 rows affected (0.74 sec)
使用 insert 命令向表中插入一些记录,
mysql> insert into DemoTable(Value) values(976); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values(67); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Value) values(67); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values(1); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable(Value) values(90); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Value) values(1); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable(Value) values(67); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Value) values(976); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values(90); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values(1); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Value) values(10); Query OK, 1 row affected (0.09 sec)
使用 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)
广告