Move node in nested set

后端 未结 13 966
孤街浪徒
孤街浪徒 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:36

    Here is a solution that lets you move a node to any position in the tree, either as a sibling or a child with just a single input parameter - the new left position (newlpos) of the node.

    Fundamentally there are three steps:

    • Create new space for the subtree.
    • Move the subtree into this space.
    • Remove the old space vacated by the subtree.

    In psuedo-sql, it looks like this:

    //
     *  -- create new space for subtree
     *  UPDATE tags SET lpos = lpos + :width WHERE lpos >= :newlpos
     *  UPDATE tags SET rpos = rpos + :width WHERE rpos >= :newlpos
     * 
     *  -- move subtree into new space
     *  UPDATE tags SET lpos = lpos + :distance, rpos = rpos + :distance
     *           WHERE lpos >= :tmppos AND rpos < :tmppos + :width
     * 
     *  -- remove old space vacated by subtree
     *  UPDATE tags SET lpos = lpos - :width WHERE lpos > :oldrpos
     *  UPDATE tags SET rpos = rpos - :width WHERE rpos > :oldrpos
     */
    

    The :distance variable is the distance between the new and old positions, the :width is the size of the subtree, and :tmppos is used to keep track of the subtree being moved during the updates. These variables are defined as:

    // calculate position adjustment variables
    int width = node.getRpos() - node.getLpos() + 1;
    int distance = newlpos - node.getLpos();
    int tmppos = node.getLpos();
    
    // backwards movement must account for new space
    if (distance < 0) {
        distance -= width;
        tmppos += width;
    }
    

    For a complete code example, see my blog at

    http://www.ninthavenue.com.au/how-to-move-a-node-in-nested-sets-with-sql

    If you like this solution, please up-vote.

提交回复
热议问题