美文网首页
Mysql 查询父节点下的左右子节点集合

Mysql 查询父节点下的左右子节点集合

作者: 赛亚人之神 | 来源:发表于2019-07-15 17:43 被阅读0次
    # 查询根节点下的所有子节点id集合
    drop function if exists getChildren;
    DELIMITER //
    CREATE FUNCTION `getChildren`(rootId varchar(50), containRoot char(1))
        RETURNS mediumtext
        READS SQL DATA
    
    BEGIN
        DECLARE sTemp mediumtext;
    
        DECLARE sTempChd mediumtext;
    
        SET sTemp = '';
    
        SET sTempChd = rootId;
    
        WHILE sTempChd is not null DO
        if sTemp != '' then
            SET sTemp = concat(sTemp, ',', sTempChd);
        else
            SET sTemp = concat(sTemp, sTempChd);
        end if ;
    
        SELECT group_concat(id) INTO sTempChd FROM organization where FIND_IN_SET(parent_id, sTempChd) > 0;
        END WHILE;
    
        if '1' != containRoot then
            set sTemp = substring(sTemp, length(rootId) + 2);
        end if;
        RETURN sTemp;
    
    END //
    DELIMITER ;
    

    使用方式:第二个参数如果是 1 表示包含父节点本身,0 表示不包含节点本身

    select getChildren('4e828f4a31a04e41957c03c10cdb49a6', '1');
    

    相关文章

      网友评论

          本文标题:Mysql 查询父节点下的左右子节点集合

          本文链接:https://www.haomeiwen.com/subject/dkaeqctx.html