簡體   English   中英

MySQL對行進行計數和排序

[英]MySQL Count and sort rows

在mysql中對一列數據進行計數和排序並將結果作為html列表輸出的最佳方法是什么?

示例數據:

**Type**
Train
Car
Car
Car
Bus
Bus

輸出應首先按最大計數項排序:

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

另外,這是在大桌子上做的不好的做法嗎?

試試這個查詢:

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

關於:

另外,這是在大桌子上做的不好的做法嗎?

這取決於你的表引擎。 MyISAM非常快,具有count(*)等聚合函數。 但是,InnoDB必須每次掃描表並計數。 所以我不建議count(*)一個大的InnoDB表。 相反,您可以在元表中存儲“count”變量,並僅在插入/更新時更新它。

select type, COUNT(*) from data group by type

試試這個查詢:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM