I have an MPTT tree of over 100,000 records stored in MySQL using lft
, rght
and parent_id
columns. Now the left/right values became corrupted, while the parent ids are still intact. It would require tons of queries to repair it in the application layer. Is there a good way to put the burden on the database and have it recalculate the left/right values using only SQL?
Just to clarify, I need to recalculate the numeric lft/rght values of a nested set, not the ids of neighboring records.
(source: mysql.com)
Using SQL Server, following script seems to be working for me.
Output testscript
Script
Testscript ##
Here's what I have adapted from @Lieven's answer, incorporating feedback from here for better performance:
Worked well with some test data, but it's still running on my 100,000 records tree, so I can't give any final judgement yet.The naïve script working directly on the physical table has abysmal performance, running for at least hours, more likely days. Switching to a temporary MEMORY table brought this time down to about an hour, choosing the right indexes cut it down to 10 mins.You are rescue me!!! I use mixed tree model, so when the day is coming, my tree (30000+) was corrupted. I learn from both of your tech, but is not recovery, just fully rebuild with lost all of sorting and reverse tree... I think, need to keep in mind older cat_left.... Just for possible integrity. So, it maybe looks like...
In all solutions provided, I was getting a problem where MySQL would prompt that it would be
Running query
for hours but nothing would happen.I then realized that if I set the lft and rght values to 1 and 2 in the first record of the tmp_tree table (the one with
parent_id = 0
), everything worked fine. Maybe the procedure needs updating to do this automatically.