是否可以在一个值上计算所有行,并获取具有最大计数(mysql)的列名?

时间:2015-09-25 05:30:58

标签: php mysql

我想根据类别列计算所有行,例如下面的类别,apple有两行,所以得到类别名称apple。谢谢。

id  user_id   category
1    2         apple
2    4        banana
3    6         apple
4    7        berry

//计算所有行,apple有两行,最大计数,因此获取类别名称apple

2 个答案:

答案 0 :(得分:3)

使用Group by计算类别。

然后按照计数的降序对结果集进行排序,并选择前1位。

<强>查询

select t.category
from 
 (
    select category,
    count(category) as cat_count
    from fruits
    group by category
 )t
 order by t.cat_count desc limit 1;

SQL Fiddle

如果多个类别具有相同的最大计数。然后,

<强>查询

select t.category
from
(
   select category,
   count(category) as cat_count
   from fruits
   group by category
)t
where t.cat_count = 
(
   select count(category) as cat_count
   from fruits
   group by category
   order by count(category) desc
   limit 1
);

SQL Fiddle

答案 1 :(得分:0)

如果你需要前1,2,3这样增加限制限制X x是1,2,3

 Select count(*) as total,category from table group by category from table order by count(*) desc