Move node in nested set

后端 未结 13 964
孤街浪徒
孤街浪徒 2020-12-07 15:06

I\'d need a MySQL query that moves a node and all its children within a nested set. I found this site, but that function just seems so illogical - there\'s no universe

13条回答
  •  离开以前
    2020-12-07 15:51

    I believe that with two extra columns to store the original Node right and left values (and all subsequent subnodes) the algorithm can be simplified. I have worked the examples with pencil and paper so if you find any holes in the algorithm please let me know.

    The target Node (The new parent of Node that you are moving) is tNode. Left value of Target Node is tNode.L and right value is tNode.R. Similarly the node you are moving is mNode and left and right values for mNode are mNode.L and mNode.R. The two extra columns are mNode.SL and mNode.SR

    So all in all we have 4 columns for manipulation R,L, SL and SR


    Step1

    calculate

    delta1 = (mNode.R - mNode.L) + 1 
    

    Step2

    Save the mNode original L and R into SL and SR columns

    - For All L between mNode.L and mNode.R 
       mNode.SL = mNode.L ; mNode.L = 0 ;
     - For All R between mNode.L and mNode.R 
       mNode.SR = mNode.R ; mNode.R = 0 ;
    

    Step3

    Do For all Nodes
    IF L > mNode.SR 
       L = L + delta1
    IF R > mNode.SR
       R = R + delta1
    

    Now the mNode is detached from Tree and Tree is adjusted without mNode.

    Step4

    calculate

    delta2 = (tNode.R - mNode.SL)
    

    Step5

    Do for all Nodes
      IF L >= tNode.R
        L = L + delta1
      IF R >= tNode.R
        R = R + delta1
    

    Now we have adjusted the Tree (and target node) to accept the number of nodes that were deleted.

    Step6

    Attach mNode at tNode and reset SL/SR column values

    Do for all Nodes
     IF SL between mNode.SL and mNode.SR
        L = mNode.SL + delta2 ; mNode.SL = 0  ;
     IF SR between mNode.SL and mNode.SR
        R = mNode.SR + delta2 ; mNode.SR = 0 ;
    

    After all these steps we should have moved mNode under the tNode.

提交回复
热议问题