在我的心里,我觉得必须有一个超级简单的递归解决方案,但我不能立即理解它.
我有一个存储在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)