I have mysql table something like this:
id | name| parent_id
---+-----+-----------
1 | aaa | 0
2 | bbb | 1
3 | ccc | 2
4 | ddd | 3
5 | eee | 3
6 | fff | 1
7 | ggg | 0
8 | hhh | 7
9 | iii | 7
I need to create a query that will fetch all hierarchy for a given id.
For Example: for input=1, result should be something like this:
id | name| parent_id
---+-----+-----------
1 | aaa | 0
2 | bbb | 1
3 | ccc | 2
4 | ddd | 3
5 | eee | 3
6 | fff | 1
For Example: for input=7, result should be something like this:
id | name| parent_id
---+-----+-----------
7 | ggg | 0
8 | hhh | 7
9 | iii | 7
I have tried something like this but don't know how to proceed. I don't know how many levels are there in hierarchy.
SELECT t1.id, t1.name, t1.parent_id, t2.name AS parent_name
FROM parent_test t1
LEFT JOIN parent_test t2 ON t1.parent_id=t2.id
WHERE t1.id=1 OR t1.parent_id=1;
Any Idea?