[英]MYSQL - Displaying rows with max count values in a group with other columns
I have been searching at lot and have found topics like similar topics but none were exactly the solutions that I was looking for. 我一直在搜寻,发现了类似主题的主题,但这些都不是我一直在寻找的解决方案。 In this case, I have a working code, but something that seems extremely hacky to me and should have a simpler and better way of getting it done. 在这种情况下,我有一个有效的代码,但是对我来说似乎很hacky,应该有一个更简单,更好的方法来完成它。
The "Test" table “测试”表
id
--
1
1
1
2
2
2
3
4
4
Nothing complex, just a simple table with some repeating id
values 没什么复杂的,只是一个带有一些重复的id
值的简单表
What I want is to group these id
together and show all the id
that are repeating the most ie 我想要的是将这些id
分组在一起,并显示所有重复次数最多的id
,即
id | count
----------
1 3
2 3
The solution that I have currently come up with 我目前想出的解决方案
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;
One way to do it with group by
and having
. 一种方法用做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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.