Getting root parent

半世苍凉 提交于 2019-12-19 08:56:36

问题


+--------+---------+-----------+
|   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


回答1:


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.




回答2:


Here is a short query doing what you're asking, assuming your table is called foo and that you want to know the root of <id>:

SELECT f.id, f.title
FROM (
    SELECT @id AS _id, (SELECT @id := parent_id FROM foo WHERE id = _id)
    FROM (SELECT @id := <id>) tmp1
    JOIN foo ON @id IS NOT NULL
    ) tmp2
JOIN foo f ON tmp2._id = f.id
WHERE f.parent_id IS NULL



回答3:


If your tree structure is more than say two layers deep you're searching for modified preorder tree traversal



来源:https://stackoverflow.com/questions/8480095/getting-root-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!