MySQL - 选择最常出现的条目

时间:2010-04-03 10:50:03

标签: mysql sorting

应该是一个简单的。

数据库 mydb 。其中一列是 mydata。

我需要哪些 SELECT 查询才能从 mydata 中选择前3个结果,但是按字母顺序排序?

例如,如果我的数据是这样的:

mydata
======
kilo (x 1 occurrence)
lima (x 9 occurrences)
golf (x 5 occurrences)
echo (x 9 occurrences)
zulu (x 8 occurrences)

如何让它返回“echo,lima,zulu”,这是按字母顺序排序的前三个频繁出现的条目?谢谢!

编辑:只是要添加,他们需要是不同的条目。谢谢!

3 个答案:

答案 0 :(得分:2)

使用内部选择选择所需的结果,使用外部选择将它们按字母顺序排列。

SELECT mydata
FROM (
    SELECT mydata
    FROM mytable
    GROUP BY mydata
    ORDER BY COUNT(mydata) DESC
    LIMIT 3
) AS T1
ORDER BY mydata

结果:

'echo'
'lima'
'zulu'

测试数据:

CREATE TABLE mytable (mydata VARCHAR(100) NOT NULL);
INSERT INTO mytable (mydata) VALUES
    ('kilo'),
    ('lima'), ('lima'), ('lima'), ('lima'), ('lima'), ('lima'), ('lima'), ('lima'), ('lima'),
    ('golf'), ('golf'), ('golf'), ('golf'), ('golf'),
    ('echo'), ('echo'), ('echo'), ('echo'), ('echo'), ('echo'), ('echo'), ('echo'), ('echo'),
    ('zulu'), ('zulu'), ('zulu'), ('zulu'), ('zulu'), ('zulu'), ('zulu'), ('zulu');

答案 1 :(得分:0)

SELECT mydata 
FROM mytable 
GROUP BY mydata 
ORDER BY count(id), mydata

不确定

答案 2 :(得分:0)

SELECT mydata
FROM mytable
GROUP BY mydata
ORDER BY COUNT(mydata) DESC, mydata
LIMIT 3