I am trying to create a database in which there can be a n
number of categories, as well as their subcategories.
At first I tried to create an adjacency model database like this
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | Electronics | NULL |
| 2 | Mobile | 1 |
| 3 | Washing Machine | 1 |
| 4 | Samsung | 2 |
+-------------+----------------------+--------+
but I ran into a problem when deleting a node, for example, how to manage child nodes for remote nodes, etc.
then I'm trying to implement the Nested Order Set Joe Celko
The table structures in each figure:
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 |
+----+-----------------+-----+-----+
but I cannot insert a new node with the correct rgt
and lft
. I use this, but it does not generate the correct values rgt
and lft
.
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;
source
share