数据库
首页 > 数据库> > mysql – 获取root父级

mysql – 获取root父级

作者:互联网

+--------+---------+-----------+
|   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的root id为id 1
我对如何做到这一点没有任何想法,有没有办法通过只使用1个查询来解决这个问题

解决方法:

你根本不会相信这一点

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.

标签:mysql,hierarchical
来源: https://codeday.me/bug/20190626/1292934.html