使用递归查询某地区所有父级,并且拼接为内容

区域表:

使用递归查询某地区所有父级,并且拼接为内容

-- 删除函数
DROP FUNCTION `getParentList`  
-- 创建函数
CREATE FUNCTION `getParentList`(subId varchar(100))   
RETURNS varchar(1000)   
BEGIN   
DECLARE fid varchar(100) default '';   -- 父级id
DECLARE temp varchar(100) default '';  -- 临时区域名称
DECLARE str varchar(1000) DEFAULT '';  -- 区域名称 
WHILE subId is not null  do   -- 循环判断父级id是否存在
        -- 获取父级id及区域名称
        select parent_id,name into fid,temp  from region WHERE id = subId; 
    IF fid is not null THEN   
                IF LENGTH(str)<=0 THEN 
                        SET str = temp;   -- 
                ELSE
                        SET str = concat(str, ',', temp);   
                END IF;   
                SET subId = fid;   
    ELSE   
        SET subId = fid;   
    END IF;   
    
END WHILE;   
    --  由于最后一次不会执行上面的循环所有就单独执行
        select parent_id,name into fid,temp  from region WHERE id = subId;
    SET str = concat(str, ',', temp);   
return str;  
END

-- 执行函数
select getParentList('2511');   

--结果

使用递归查询某地区所有父级,并且拼接为内容