深度在mysql和closure桌子树中
-
21-12-2019 - |
题
在将新节点插入树时,我将如何填充闭合表的深度/长度列?
祖先和后代的值是来自另一个表的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}';
.
是什么最好的方法?谢谢!
解决方案
向第一个选择添加深度+ 1。
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;
. 不隶属于 StackOverflow