MySQL: Counting and Filtering Child Elements

If you have a category table similar like the one below, and have the need to count the children elements, you can do it following the example below.

IDCATEGORY_NAMEPARENT_ID
1Cars0
2Opel1
3Planes0
4Mercedes1
5Cessna3
6Airbus3
7Boats0
SELECT
    T1.ID,
    T1.CATEGORY_NAME,
    COUNT(T2.ID) AS CHILDREN
FROM
    TABLE AS T1
    LEFT JOIN TABLE AS T2 ON T1.ID = T2.PARENT_ID
GROUP BY
    T1.ID

As you can see, we did a self join of the same table and created a relationship with the table alias T1.ID with the table alias T2.PARENT_ID.

And, if you want, for example to get the categories with no children, just do it like this, by adding the two final lines:

SELECT
    T1.ID,
    T1.CATEGORY_NAME,
    COUNT(T2.ID) AS CHILDREN
FROM
    TABLE AS T1
    LEFT JOIN TABLE AS T2 ON T1.ID = T2.PARENT_ID
GROUP BY
    T1.ID
HAVING
    CHILDREN = 0
Exit mobile version