在SQL中选择前5个最多计数国家/地区

时间:2016-02-18 02:54:41

标签: mysql sql database

您好我需要从DB中获取大多数可数国家/地区。看起来如何:

id name country
1  fsdf Sweden
2  dfdf Brazil
3  fgfg Sweden
4  gfgg Germany
5  fgfg Germany
6  fgfg Poland
7  fdff Germany
8  iuii Brazil
9  tyyt Sweden
10 tyut Sweden
11 gfgf Germany
12 fdff Holland

我希望得到这样的输出 - 最重要的是:

1 Germany count 4
2 Sweden count 4
3 Brazil count 2
4 Poland count 1
5 Holand coun 1

我尝试了类似的东西但没有工作

$top5 = $mysqli -> query ("SELECT top 5 country, count(*)
from list_ots
group by country
order by country desc");

while ($row = mysql_fetch_assoc($top5)) {
    echo $row["country"];
}
mysql_free_result($result);

3 个答案:

答案 0 :(得分:4)

MySQL中的正确语法使用LIMIT,而不是TOP

select country, count(*) as cnt
from list_ots
group by country
order by cnt desc
limit 5;

答案 1 :(得分:4)

使用必须使用SELECT country, count(*) as count FROM list_ots GROUP BY country ORDER by count desc LIMIT 5; 才能获得前5名

{{1}}

答案 2 :(得分:0)

选择前5个国家,计数(*)作为CountryCount FROM list_ots按国家/地区按国家/地区顺序排列