gpt4 book ai didi

mysql - 在 MySQL/PHP 中实现嵌套顺序集

转载 作者:可可西里 更新时间:2023-11-01 06:47:34 24 4
gpt4 key购买 nike

我正在尝试创建一个数据库,其中可能有 n 个类别及其子类别。

首先我尝试像这样创建邻接模型数据库

+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | Electronics | NULL |
| 2 | Mobile | 1 |
| 3 | Washing Machine | 1 |
| 4 | Samsung | 2 |
+-------------+----------------------+--------+

但是,我在删除节点时遇到了一个问题,比如如何管理已删除节点的子节点等。

然后我尝试通过 Joe Celko 实现嵌套订单集 sample_structure

各图中的表结构:

Figure 1:
+----+-------------+-----+-----+
| id | name | lft | rgt |
+----+-------------+-----+-----+
| 1 | Electronics | 1 | 2 |
+----+-------------+-----+-----+

Figure 2:
+----+-------------+-----+-----+
| id | name | lft | rgt |
+----+-------------+-----+-----+
| 1 | Electronics | 1 | 4 |
+----+-------------+-----+-----+
| 2 | Mobile | 2 | 3 |
+----+-------------+-----+-----+

Figure 3:
+----+-----------------+-----+-----+
| id | name | lft | rgt |
+----+-----------------+-----+-----+
| 1 | Electronics | 1 | 6 |
+----+-----------------+-----+-----+
| 2 | Mobile | 2 | 3 |
+----+-----------------+-----+-----+
| 3 | Washing Machine | 4 | 5 |
+----+-----------------+-----+-----+

Figure 4:
+----+-----------------+-----+-----+
| id | name | lft | rgt |
+----+-----------------+-----+-----+
| 1 | Electronics | 1 | 8 |
+----+-----------------+-----+-----+
| 2 | Mobile | 2 | 5 |
+----+-----------------+-----+-----+
| 3 | Washing Machine | 6 | 7 |
+----+-----------------+-----+-----+
| 4 | Samsung | 3 | 4 |
+----+-----------------+-----+-----+

但我无法插入具有正确 rgtlft 的新节点。我正在使用它,但它没有生成正确的 rgtlft 值。

LOCK TABLE nested_category WRITE;

SELECT @myRight := rgt FROM nested_category
WHERE name = 'Mobile';

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('LG', @myRight + 1, @myRight + 2);

UNLOCK TABLES;

最佳答案

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/我认为是您的源代码吗?

你没有使用好的查询,这个是add a brother node

您在添加子节点之后:

LOCK TABLE nested_category WRITE;

SELECT @myLeft := lft FROM nested_category
WHERE name = 'Mobile';

UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myLeft;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myLeft;

INSERT INTO nested_category(name, lft, rgt) VALUES('LG', @myLeft + 1, @myLeft + 2);

UNLOCK TABLES;

关于mysql - 在 MySQL/PHP 中实现嵌套顺序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43201104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com