Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我需要编写如下 SQL 语句:
我有一张桌子,里面有很多物品,每个物品都有一个类别。总共有3个类别。
我需要选择 DISTINCT 类别,然后按每个类别中的项目数对它们进行排序。
这会是一个好方法吗?还是太慢了?
SELECT DISTINCT category, count(*) AS counter FROM item_descr GROUP BY category ORDER BY counter DESC
DISTINCT不需要,因为您正在使用GROUP BY category:
DISTINCT
GROUP BY category
SELECT category, count(*) AS counter FROM item_descr GROUP BY category ORDER BY counter DESC
GROUP BY就是做你想做的事。DISTINCT是多余的。
GROUP BY
如果您希望获得良好的性能,尤其是在较大的表上,那么对类别进行索引非常重要。