mysql-显示组中具有最大计数值的行和其他列

11dmarpk  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(254)

我一直在搜索很多,并找到类似的主题,但没有一个正是我所寻找的解决方案的主题。在这种情况下,我有一个工作的代码,但有些东西似乎非常黑客我,应该有一个更简单,更好的方式来完成它。
“测试”表

id
--
 1
 1
 1
 2
 2
 2
 3
 4
 4

没什么复杂的,只是一张简单的table,上面有一些重复的内容 id 价值观
我想把这些 id 一起展示 id 重复次数最多的

id | count
----------
 1       3
 2       3

我目前提出的解决方案

select
    @max := max(count) as count
from (
    select 
        id,
        count(id) as count
    from 
        test
    group by
        id
)
as 
    inner_table;

select
    id, count
from (
    select 
        id,
        count(id) as count
    from 
        test
    group by
        id
)
as 
    inner_table
where count = @max;
weylhg0b

weylhg0b1#

一种方法是 group by 以及 having .

select id,count(*) as cnt
from t
group by id
having count(*)=(select count(*) as cnt 
                 from t 
                 group by id
                 order by cnt desc
                 limit 1)

相关问题