BlogProgramming

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

Artigos Relacionados

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *

Este site utiliza o Akismet para reduzir spam. Fica a saber como são processados os dados dos comentários.

Botão Voltar ao Topo
João Clérigo - Photography
Fechar

AdBlocker Detetado
AdBlocker Detected

Por favor ajude este website permitindo a visualização de alguns anúncios. Obrigado. Please help this website allowing the view of some advertising. Thank you!