找出包含其他列值中最大计数值的记录的 MySQL 查询?
为此,请使用 GROUP BY HAVING 子句。让我们首先创建一个表 -
mysql> create table DemoTable ( Value int ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(88); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-------+ | Value | +-------+ | 88 | | 88 | | 88 | | 99 | | 99 | | 99 | | 99 | | 100 | | 100 | | 88 | | 88 | +-------+ 11 rows in set (0.00 sec)
以下是显示组中具有最大计数值并带有其他列的记录的查询。这里,我们在一列中有重复的值,并且我们正在对这些值进行排序。在 ORDER BY DESC 之后,我们获取第一个值,并将其计数显示在新列“NumberOfCount”中 -
mysql> select Value,count(*) as NumberOfCount from DemoTable group by Value having count(*)=(select count(*) as NumberOfCount from DemoTable group by Value order by NumberOfCount desc limit 1);
这将产生以下输出 -
+-------+---------------+ | Value | NumberOfCount | +-------+---------------+ | 88 | 5 | +-------+---------------+ 1 row in set (0.00 sec)
广告