一、数据准备
随便创建一个父子结构表,eg:
 
二、开始创建function
(如果没权限执行,执行下面这句)
1、根据子节点找父亲路径:
创建一个function getPatentList()
DELIMITER $$
set global log_bin_trust_function_creators=1;
DROP FUNCTION IF EXISTS getPatentList$$
CREATE FUNCTION getPatentList(rootId varchar(20)) RETURNS varchar(100)
BEGIN
DECLARE i varchar(100) default '';  
DECLARE j varchar(1000) default rootId;  
 
WHILE rootId is not null  do  
    SET i =(SELECT parent_id FROM dictionary_info_relation WHERE `status`=1 and children_id
		 = rootId);  
    IF i is not null THEN  
        SET j = concat(i, '/', j);  
        SET rootId = i;  
    ELSE  
        SET rootId = i;  
    END IF;  
END WHILE;  
return j; 
END $$
DELIMITER ;
 
随便传入一个节点,查询到根节点路径调用sql:
 select getPatentList(670222424395143);
结果(查找到跟节点路径):670220694834566/670221259476353/670222424395143
2、根据父节点找子节点:
创建一个function getChildList()
DELIMITER $$
set global log_bin_trust_function_creators=1;
DROP FUNCTION IF EXISTS getChildList$$
CREATE FUNCTION getChildList(rootId varchar(20)) RETURNS varchar(100)
BEGIN  
DECLARE str varchar(2000); 
DECLARE cid varchar(100);  
SET str = '$';  
SET cid = rootId;  
WHILE cid is not null DO  
    SET str = concat(str, '/', cid);  
    SELECT group_concat(children_id) INTO cid FROM dictionary_info_relation where FIND_IN_SET(parent_id, cid) > 0;  
END WHILE;  
RETURN str;  
END $$
DELIMITER ;
 
随便传入一个节点,查询到根节点路径调用sql:
 select getChildList(670221259476353);
结果(查找到根节点路径【670221259476353下边多个子节点,会逗号分隔】):
 $/670221259476353/670222424395143,11
三、执行效果:
1、根据子节点找父亲路径:

 
2、根据父节点找子节点:












