MySQL查询最大重复值

时间:2017-11-14 18:23:20

标签: mysql

| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |

mysql query for maximum duplicate value非常相似我需要拥有最多条目的b_id(s)。

发布的解决方案

select b_id, count(b_id) 
from books 
group by b_id 
order by count(b_id) desc
limit 1;

对我不起作用,因为它只显示重复最长时间的b_ids之一。 我在这里要求的结果是

| b_id | reps | 
+------+------+
|   10 |    3 | 
|   40 |    3 |

3 个答案:

答案 0 :(得分:2)

在这里,将您的查询移动到交叉连接部分,该部分为您提供最大计数值,然后使用与主查询相同的查询匹配内部查询计数来获取具有相同最大计数的b_id

select a.b_id,maxcountb
from books a
cross join (
    select  count(b_id) maxcountb
    from books 
    group by b_id 
    order by maxcountb desc
    limit 1
) b
group by a.b_id
having count(a.b_id) =maxcountb

Demo

另一种重写上面的方法,以便更好地理解

select a.b_id,count(a.b_id) maxcounta
from books a
group by a.b_id
having maxcounta =(
  select  count(b_id) maxcountb
  from books 
  group by b_id 
  order by maxcountb desc
  limit 1
)

Demo

答案 1 :(得分:1)

试试这个..

 select b_id, count(b_id) 
    from books 
    group by b_id 
    having count(b_id) = (select count(b_id) as count_bid from books group by b_id order by count_bid desc limit 1)

答案 2 :(得分:1)

select b_id, count(b_id) 
    from books 
    group by b_id 
    having count(b_id) = (select max(count(b_id)) as count_bid from books);