Move node in nested set

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

    See the article in my blog for storing and using hierarchical data in MySQL:

    • Hierarchical queries in MySQL

    To move a whole branch in such a table, you'll just need to update the root's parent (a single row)

    You'll need to create a function:

    CREATE FUNCTION hierarchy_connect_by_parent_eq_prior_id(value INT) RETURNS INT
    NOT DETERMINISTIC
    READS SQL DATA
    BEGIN
            DECLARE _id INT;
            DECLARE _parent INT;
            DECLARE _next INT;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET @id = NULL;
    
            SET _parent = @id;
            SET _id = -1;
    
            IF @id IS NULL THEN
                    RETURN NULL;
            END IF;
    
            LOOP
                    SELECT  MIN(id)
                    INTO    @id
                    FROM    t_hierarchy
                    WHERE   parent = _parent
                            AND id > _id;
                    IF @id IS NOT NULL OR _parent = @start_with THEN
                            SET @level = @level + 1;
                            RETURN @id;
                    END IF;
                    SET @level := @level - 1;
                    SELECT  id, parent
                    INTO    _id, _parent
                    FROM    t_hierarchy
                    WHERE   id = _parent;
            END LOOP;
    END
    

    and use it in a query:

    SELECT  CONCAT(REPEAT('    ', level - 1), CAST(hi.id AS CHAR)) AS treeitem, parent, level
    FROM    (
            SELECT  hierarchy_connect_by_parent_eq_prior_id(id) AS id, @level AS level
            FROM    (
                    SELECT  @start_with := 0,
                            @id := @start_with,
                            @level := 0
                    ) vars, t_hierarchy
            WHERE   @id IS NOT NULL
            ) ho
    JOIN    t_hierarchy hi
    ON      hi.id = ho.id
    
    0 讨论(0)
提交回复
热议问题