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

Dao*_*jao 2 mysql sql group-by count max

我一直在搜索很多,并找到类似主题的主题,但没有一个是我正在寻找的解决方案.在这种情况下,我有一个工作代码,但对我来说似乎非常hacky,应该有一个更简单,更好的方法来完成它.

"测试"表

id
--
 1
 1
 1
 2
 2
 2
 3
 4
 4
Run Code Online (Sandbox Code Playgroud)

没有什么复杂的,只是一个带有一些重复id值的简单表

我想要的是将这些id组合在一起并显示所有id重复最多的东西

id | count
----------
 1       3
 2       3
Run Code Online (Sandbox Code Playgroud)

我目前提出的解决方案

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;
Run Code Online (Sandbox Code Playgroud)

Vam*_*ala 5

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)
Run Code Online (Sandbox Code Playgroud)