在MySQL/PHP中实现嵌套订单集

jpm*_*jpm 6 mysql sql algorithm tree hierarchical-data

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

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

+-------------+----------------------+--------+
| category_id | name                 | parent |
+-------------+----------------------+--------+
|           1 | Electronics          |   NULL |
|           2 | Mobile               |      1 |
|           3 | Washing Machine      |      1 |
|           4 | Samsung              |      2 |
+-------------+----------------------+--------+
Run Code Online (Sandbox Code Playgroud)

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

然后我试图实现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   |
+----+-----------------+-----+-----+
Run Code Online (Sandbox Code Playgroud)

但我无法插入新节点用正确的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;
Run Code Online (Sandbox Code Playgroud)

Bla*_*lag 4

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

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

你正在追寻add a child 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;
Run Code Online (Sandbox Code Playgroud)