Answer the question
In order to leave comments, you need to log in
How to restore lft and rgt fields in nested set table by root_id?
There is a table built according to the nested set model. The lft and rgt fields are damaged in it, but the root_id is preserved. How can I restore (recalculate) the values of the lft and rgt fields using only SQL (MySQL) tools?
+----+---------+-------+-------+
| id | root_id | lft | rgt |
+----+---------+-------+-------+
| 1 | 1 | NULL | NULL |
+----+---------+-------+-------+
| 2 | 1 | NULL | NULL |
+----+---------+-------+-------+
| 3 | 2 | NULL | NULL |
+----+---------+-------+-------+
| 4 | 4 | NULL | NULL |
+----+---------+-------+-------+
| 5 | 4 | NULL | NULL |
+----+---------+-------+-------+
Answer the question
In order to leave comments, you need to log in
For the given table - in any way. Nodes 1 and 4 have themselves as parents.
In the general case, add the `level` column - the level of the node and, since everything needs to be done using SQL, write a stored procedure that sets the node level for each line and rebuilds the `lft` and `rgt` fields for each line in ascending order of `level` ( see article ).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question