小编Jon*_*bie的帖子

从祖先列表中构建树的最简单方法

在我的心里,我觉得必须有一个超级简单的递归解决方案,但我不能立即理解它.

我有一个存储在SQL中的树作为闭包表.树看起来像:(1(2(3),4)),语言是MySQL的SQL和PHP 5.3.

因此,闭包表是:

+----------+------------+
| ancestor | descendant |
+----------+------------+
|        1 |          1 | 
|        2 |          2 | 
|        3 |          3 | 
|        4 |          4 | 
|        1 |          2 | 
|        1 |          3 | 
|        1 |          4 | 
|        2 |          3 | 
+----------+------------+
Run Code Online (Sandbox Code Playgroud)

我可以很容易地查询祖先:

 SELECT descendant AS id, GROUP_CONCAT(ancestor) as ancestors FROM
 closure GROUP BY (descendant);

 +----+-----------+
 | id | ancestors |
 +----+-----------+
 |  1 | 1         | 
 |  2 | …
Run Code Online (Sandbox Code Playgroud)

php mysql tree closures

5
推荐指数
1
解决办法
2508
查看次数

标签 统计

closures ×1

mysql ×1

php ×1

tree ×1