[英]How to get the item that has the highest number of occurence in a mysql table
我有一個產品表,如下所示:
id name quantity
1 shoe 2
2 pen 1
3 shoe 1
4 glass 3
5 pen 4
6 shoe 2
我想獲取在表中出現次數較多的項目及其占用的行數或在表中重復的次數。 在上表的情況下, shoe
出現的次數最多,即3次。 我需要可以允許我執行此操作的 mysql 查詢(在上述情況下返回 3)。
請考慮性能,因為此查詢將在具有大約 1000 萬條記錄的表上執行。 謝謝!
SELECT name,count(*) FROM products GROUP BY name ORDER BY count(*) DESC limit 1
這可能有效
一個基本的GROUP BY
會做:
select top 1 name, count(name), sum(quantity)
from XX
group by name
order by count(name) desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.