获取根父级
+--------+---------+-----------+
| id | title | parent_id |
+--------+---------+-----------+
| 1 | Lvl-1 | null |
+--------+---------+-----------+
| 2 | Lvl-2 | null |
+--------+---------+-----------+
| 3 | Lvl-11 | 1 |
+--------+---------+-----------+
| 4 | Lvl-12 | 1 |
+--------+---------+-----------+
| 5 | Lvl-121 | 4 |
+--------+---------+-----------+
我实际上如何获取每行的根父级
例如,id 5
的行的父级为 id 4
,而 id 4
的父级为 id 1
,因此id 5
的根 ID 是 id 1
我不知道如何做到这一点,有没有办法通过仅使用 1 个查询来解决这个问题
+--------+---------+-----------+
| 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个简短的查询,执行您所要求的操作,假设您的表名为
foo
并且您想知道
的根: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>
:你根本不会相信这个
我在 DBA StackExchange(2011 年 10 月 24 日)上写了一篇关于如何实现这一目标的文章使用存储过程编程。我还提供了一些示例数据和结果。
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.
如果您的树结构深度超过两层,您正在搜索修改后的先序树遍历
If your tree structure is more than say two layers deep you're searching for modified preorder tree traversal