2010-05-10 64 views
1

對mysql中的數據列進行計數和排序並將結果輸出爲html列表的最佳方式是什麼?MySQL計數和排序行

示例數據:

**Type** 
Train 
Car 
Car 
Car 
Bus 
Bus 

輸出應與計數最大的項目首先進行排序:

- car(3) 
- bus(2) 
- train (1) 

而且,這是不好的做法做就大表?

回答

7

嘗試此查詢:

select type, count(*) from vehicles group by type order by count(*) desc 

在問候:

而且,這是不好的做法做就大表?

這取決於你的表引擎。 MyISAM速度非常快,集成功能如count(*)。但是,InnoDB必須每次掃描表並計數。所以我不建議count(*)一個大的InnoDB表。相反,您可以在元表中存儲「count」變量並僅在插入/更新時進行更新。

2
select type, COUNT(*) from data group by type 
+0

短而甜! – Aditya 2010-05-10 16:24:37

0

嘗試此查詢:

select t.type, count(t.type) as typecount from type as t group by type order by typecount desc 

希望幫助這個查詢...!