我想从MySQL数据库表中获取某种十大列表。
这是一个例子。假设我有这张桌子:

ID  Username    Town
 1  foo         Munich
 2  bar         Kolding
 3  herp        Bordeaux
 4  derp        Bordeaux
 5  test        Cologne
 6  bla         Munich
 7  blob        Bordeaux


现在,我想在“城镇”中获得最常见的条目,如下所示:

Bordeaux  3
Munich    2
Cologne   1
Kolding   1


什么样的查询可以做到这一点?

最佳答案

这个怎么样。

SELECT Town, Count(1) as TownCount
FROM myTable
GROUP BY Town
ORDER BY TownCount DESC;


如果只需要10条记录,请使用

SELECT Town, Count(1) as TownCount
FROM myTable
GROUP BY Town
ORDER BY TownCount DESC
LIMIT 10;

10-08 09:35