I need to compose a SQL statement as follows:
I have a table with many items, each item having a category. In total there are 3 categories.
I need to select the DISTINCT categories and then order them by number of items within each category.
Would this be a good way? Or too slow?
SELECT DISTINCT category, count(*) AS counter
FROM item_descr
GROUP BY category
ORDER BY counter DESC
The DISTINCT
is not needed since you are using GROUP BY category
:
SELECT category, count(*) AS counter
FROM item_descr
GROUP BY category
ORDER BY counter DESC
The GROUP BY
is doing what you want. DISTINCT
is redundant.
如果要获得良好的性能(尤其是在较大的表上),则在类别上建立索引非常重要。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.