在向树中插入新节点时,我将如何填充闭包表的深度/长度列?

祖先和后代中的值是来自另一个表的ID,这些ID表示要以树形结构排列的页面。

关闭表:

ancestor    descendant     depth
1               1            0
1               2            1
1               3            1
1               4            1
2               2            0
3               3            0
4               4            0

这将正确插入祖先和后代,但我不确定如何填充深度列
插入查询:
INSERT INTO closure_tree_path (ancestor, descendant)
SELECT ancestor, '{$node_id}' FROM closure_tree_path
WHERE descendant = '{$parent_id}'
UNION ALL SELECT '{$node_id}', '{$node_id}';

解决这个问题的最佳方法是什么?谢谢一堆!

最佳答案

将 depth+1 添加到第一个 SELECT。

INSERT INTO closure_tree_path (ancestor, descendant, depth)
SELECT ancestor, '{$node_id}', depth+1 FROM closure_tree_path
WHERE descendant = '{$parent_id}'
UNION ALL SELECT '{$node_id}', '{$node_id}', 0;

10-08 09:05