管理 MySQL 中的分层数据
我看到这篇文章 http://mikehillyer.com/articles/managing-hierarchical -data-in-mysql/ 但我没有得到“添加新节点”部分。
它说我可以这样做来添加一个新节点:
SELECT @myRight := rgt FROM nested_category
WHERE name = 'TELEVISIONS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myRight;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myRight;
INSERT INTO nested_category(name, lft, rgt) VALUES('GAME CONSOLES', @myRight + 1, @myRight + 2);
- 在运行时我会知道父节点而不是同级节点。
- 如果该节点根本没有兄弟节点怎么办,我该如何添加它?
- 如何添加新的根节点?
I came across this article http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ but I didn't get the "Adding New Nodes" part.
It says I can do this to add a new node:
SELECT @myRight := rgt FROM nested_category
WHERE name = 'TELEVISIONS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myRight;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myRight;
INSERT INTO nested_category(name, lft, rgt) VALUES('GAME CONSOLES', @myRight + 1, @myRight + 2);
- At the runtime I'll know the parent not the sibling.
- What if the node doesn't have siblings at all, how can I add it?
- How can I add a new root node?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
兄弟姐妹并不重要。您只需通过其parent_id 即可添加新节点。
它的工作原理如下:将节点添加为父节点的最左子节点,然后更新节点的 lft 和 rgt,使其位置位于新节点的右侧(树的所有节点)。现在树的所有节点都正在正确更新。
要添加新的根节点,您应该将其parent_id 设置为NULL。
我希望这对你有用。
it doesn't matter the siblings. u can add the new node by just having its parent_id.
it works like this : add the node as the most left child of the parent, then update the lft and rgt of the nodes that their positions are right of the new node(all nodes of the tree). all nodes of the tree are being updated currectly now.
for adding a new root node, u should set its parent_id to NULL.
I hope thats be useful for u.