2014-04-12 27 views
7

当向树插入新节点时,我将如何填充闭合表的深度/长度列?MYSQL和闭合表树的深度

祖先和后代中的值是来自另一个表的代表要在树结构中排列的页面的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}'; 

什么是最好的方式去做这个?谢谢一堆!

回答

10

将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; 
+0

该查询不起作用。 – Guy

+0

我忘了将深度列放入INSERT部分。更新。 – tazer84

+0

已经占了那个。不起作用。 – Guy