I have a fairly straightforward self-referenced table like the following:
TABLE 1
id parent_id
1 NULL
2 1
3 NULL
4 1
5 2
6 5
7 2
8 4
I need to generate a new table where for each element, all their descendants are associated. See this example:
TABLE 2
element descendants
1 2
1 5
1 6
1 7
1 4
1 8
2 5
2 6
2 7
5 6
4 8
Notice that 3
is not present because it doesn't have any children.
How can I achieve this using a stored procedure? I can get a direct parent-child relation, but I'm having a hard time getting all descendants for a given element.
(real world table is ~15k rows & ~7 level hierarchy, but level it is not predefined so lets assume is N)