2016-02-18 27 views
2

您好,我需要从DB中提取大部分可数国家。怎么看起来像:在SQL中选择排名前5的最多国家

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); 

回答

4

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

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

使用必须使用LIMIT获得前5名:

​​
0

选择前5个国家,COUNT(*)作为CountryCount FROM list_ots集团按国家排序CountryCount说明