mySQL查询找到最重复的值

时间:2011-04-07 13:10:43

标签: mysql

我有一个包含多行的表,对于每一行我都需要知道最常见的值。

示例:

row_1有

car
boat
car
car
truck
truck
plane
car
car

作为其价值观。

我需要知道什么是最常见的价值(在这种情况下是汽车)。 我有几个想法,但因为我必须为30行做这个,我想要一个简单而不是CPU密集的查询。

2 个答案:

答案 0 :(得分:21)

获取值列表及其出现次数:

select col_name, count(col_name) c from table
group by col_name
order by c desc;

如果您只想要最常见的值:

select col_name, count(col_name) c from table
group by col_name
order by c desc
limit 1;

答案 1 :(得分:4)

我以这样的方式编写查询:如果有更多项目具有相同的最高出现次数,您将看到它们全部,而不仅仅是其中之一。

select item
from table
group by item
having count(item) = (
select count(item) as great
from table
group by item order by great desc limit 1)