Let's say there is a table called people with the following columns:
- person_id (integer)
- parent_person_id (integer)
- name (varchar)
Now, let's say the table has being populated and the name values are just letters (A, B, C, D ...). Considering the parents of each we end up with a hierarchical tree like the one bellow. The values are on the format:
person_id, parent_person_id, name
- 1, 1, A
- 2, 2, B
- 3, 2, C
- 4, 3, D
- 5, 2, E
- 6, 5, F
- 7, 6, G
- 8, 6, H
- 6, 5, F
- 3, 2, C
Consider on the structure above, A & B as first generation, C & E as second generation, D & F as third generation and G & H as fourth generation. For the first generation elements, the parent_person_id is equal to the person_id of the element.
I need to write a query that allows me to select the names from a certain generation(first, second, third, fourth, etc) of the tree. As a result I could get a table with the names of the user from a certain generation. For example:
1st Generation
person name | parent name
A | A
B | B
2nd Generation
person name | parent name
C | B
E | B
3rd Generation
person name | parent name
D | C
F | E
4th Generation
person name | parent name
G | F
H | F
I would like to pass a parameter to define each generation should be listed as child on the following query.
SELECT
child.name as 'person name',
parent.name as 'parent name'
FROM
people as child
JOIN
people as parent
ON
child.parent_person_id = parent.person_id
WHERE
-- I NEED HELP HERE :)
;
Does anyone have any ideas on how I can achieve this? Any help is welcome.