2016-02-18 29 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說明