Search code examples
mysqlhierarchical

Getting root parent


+--------+---------+-----------+
|   id   | title   | parent_id |
+--------+---------+-----------+
|    1   | Lvl-1   |   null    |
+--------+---------+-----------+
|    2   | Lvl-2   |   null    |
+--------+---------+-----------+
|    3   | Lvl-11  |     1     |
+--------+---------+-----------+
|    4   | Lvl-12  |     1     |
+--------+---------+-----------+
|    5   | Lvl-121 |     4     |
+--------+---------+-----------+

How do i actualy get root parent for each row
For example, row with id 5 have parent with id 4 and id 4 have parent with id 1, so root id for id 5 is id 1
I dont have any idea on how to do it and is there a way to solve this by using only 1 query


Solution

  • You are simply not going to believe this

    I wrote a post in the DBA StackExchange (October 24, 2011) on how to pull this off using Stored Procedure programming. I also included some sample data and the results.