mysql ORDER结果BY列中出现次数

时间:2010-07-10 22:19:00

标签: mysql

我有一个数据库,它将收到大量信息,但最重要的是,它会收到每行的城市名称。以下示例:

id         city
1          London
2          Manchester
3          London
4          Brighton
5          Oxford
6          Oxford
7          London

我想从此表中仅选择城市名称,按照最常出现的顺序显示前3个结果。

到目前为止,我正在使用下面的查询:

SELECT N.city, COUNT(*) AS howmany
FROM ( SELECT DISTINCT city FROM events ) AS N,
events AS T
WHERE N.city = T.city
GROUP BY N.city
ORDER BY howmany
LIMIT 0,2 

3 个答案:

答案 0 :(得分:2)

您可以将现有查询简化为对事件表的单一访问,而无需将其连接到自身:

SELECT N.city, 
       COUNT(N.city) AS howmany 
  FROM events AS N
 GROUP BY N.city 
 ORDER BY howmany 
 LIMIT 3

如果您不想返回计数,请尝试:

SELECT N.city
  FROM events AS N
 GROUP BY N.city 
 ORDER BY COUNT(N.city)
 LIMIT 3

答案 1 :(得分:2)

您不需要额外加入GROUP BY已经为您处理DISTINCT方面。

SELECT city, COUNT(*) AS howmany
FROM 
events
GROUP BY city
ORDER BY howmany DESC
LIMIT 0,3 

答案 2 :(得分:2)

如果您只想在最终结果中加入“城市”字段:

SELECT city FROM (
  SELECT city, COUNT(*) as ccount
  FROM events
  GROUP BY city
)
ORDER BY ccount DESC
LIMIT 3

如果您不关心最终结果中的字段,只要城市就是其中之一,它就更简单了:

SELECT city, COUNT(*) as ccount
FROM events
GROUP BY city
ORDER BY ccount DESC
LIMIT 3