使用 MySQL 获取单独列中不同值的最大计数
mysqlmysqli database更新于 2023/11/26 15:40:00
为此使用 COUNT() 函数和 GROUP BY 子句。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Name varchar(100) -> ); Query OK, 0 rows affected (0.69 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
这将产生以下输出 −
+-------+ | Name | +-------+ | John | | Sam | | John | | Mike | | John | | Sam | | Carol | +-------+ 7 rows in set (0.00 sec)
这是 SQL 中对不同值的最大计数的查询 −
mysql> select Name, count(*) as freq from DemoTable group by Name order by count(*) desc limit 1;
输出
这将产生以下输出 −
+------+------+ | Name | freq | +------+------+ | John | 3 | +------+------+ 1 row in set (0.00 sec)