2013-12-10 108 views
0

假設我有一個名爲「id」,「name」和「type」的列名爲animals的表。最後一列裝滿牛,雞,馬,豬,大象,河馬等SQL計數行並按順序顯示

我要的是一個計數類型的數量,並顯示他們以這樣的查詢...

雞45頭
奶牛40
馬5
等等

現在我只是想顯示10的最高金額。我用這個查詢...

$result = mysql_query("SELECT * FROM animals ORDER BY id DESC LIMIT 0, 10"); 

while($row = mysql_fetch_array($result)) 
{ 

echo "<tr><td>" . $row['type']. "</td><td align=\"right\"></td></tr>"; 
} 

上面的代碼只顯示類型,如









etc ...

我不知道如何使用計數器並按最高值排序。

+0

可能複製http://stackoverflow.com/questions/12789396/how -to-get-multiple-counts-with-one-sql-query – Naeem

回答

1

請嘗試以下查詢:

Select type, count(type) as type_count FROM animals GROUP BY type ORDER BY type_count desc LIMIT 0, 10 
+0

擊敗了我! – AdRock

+0

感謝這工作! – user2959441

0

試試這個:

select name, count(name) as total from animals 
group by name order by total desc limit 10 
0

嘗試:

select 
    top 10 type, Count(*) 
from 
    animals 
group by 
    type 
order by 
    count(*) desc,type