Think of the nested sets model as of an XML
file with lft
and rgt
being the lines where the staring and ending tags reside:
1 <root>
2 <item1>
3 </item1>
4 </root>
To insert a new subtag into the root
, you'll need to shift down all subsequent records:
1 <root>
2 <item1>
3 </item1>
4 <item2>
5 </item2>
6 </root>
So you'll need to calculate the item2.lft
and item2.rgt
(which are the item2.rgt + 1
and item1.rgt + 2
, accordingly), and then increment all lft
and rgt
of all items which are greater than the item1.rgt
:
UPDATE mytable
SET rgt = rgt + 2
WHERE rgt > item1.rgt
UPDATE mytable
SET lft = lft + 2
WHERE rgt > item1.rgt