I have a table called foo with these fields:
- id
- type
- parentId
I want to select a list of parent IDS, in the descending order of their COUNT(*) of how many times they appear in the table. Something like this:
SELECT DISTINCT parentId FROM `foo`
ORDER BY (COUNT(parentId) DESC where parentId = parentId)
How can this be done in the most efficient way and putting the least load on the server?
There can be thousands-hundreds of thousands of records in the table, so manually going through each record is not acceptable..
Simply by applying a
GROUP BYclause, and assuming you have an index ,FOREIGN KEY, orPRIMARY KEYonparentId, the performance should be quite good. (parentIdlooks like it is likely aFORIEGN KEY, so be sure to define the constraint to enforce indexing).