Say we have a table which has two columns, id
and id_parent
. The field id_parent
references to an id
of the same table. If id_parent
is NULL
, we consider that entry to be the first element of a chain.
The question is: is there a query to get the different chains and how many elements are there in each one?
E.g., given the table
id id_parent
1 NULL
2 NULL
3 1
4 3
5 NULL
6 5
7 4
The output would be
id_first_el num_of_els
1 4
2 1
5 2
Constraints: no circularity, no bifurcations (id_parent
is unique).