How to return rows listed in descending order of COUNT(*)?

前端 未结 2 433
生来不讨喜
生来不讨喜 2021-01-12 12:35

I have a table called foo with these fields:

- id

- type

- parentId

I want to select a list of parent IDS, in the descending

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 13:08

    Simply by applying a GROUP BY clause, and assuming you have an index , FOREIGN KEY, or PRIMARY KEY on parentId, the performance should be quite good. (parentId looks like it is likely a FORIEGN KEY, so be sure to define the constraint to enforce indexing).

    SELECT `parentId`
    FROM `foo`
    GROUP BY `parentId`
    ORDER BY COUNT(*) DESC
    

提交回复
热议问题