MYSQL 自定义函数,查询节点所有父节点、查询节点所有子节点
作者:互联网
一.查询所有父节点。
1.sql代码
select getParentIdList(3402)
2.创建函数
CREATE FUNCTION `getParentIdList`(rootId INT) RETURNS varchar(1000) CHARSET utf8mb4
DETERMINISTIC
BEGIN
DECLARE fid INT default 0;
DECLARE str varchar(1000) default rootId;
WHILE rootId is not null do
SET fid =(SELECT pid FROM t_space WHERE id = rootId);
IF fid is not null THEN
SET str = concat(str, ',', CAST(fid AS CHAR));
SET rootId = fid;
ELSE
SET rootId = fid;
END IF;
END WHILE;
return str;
END
二.查询所有子节点
1.sql代码
select getChildrenIdList(1)
2.创建函数
CREATE FUNCTION `getChildrenIdList`(rootId INT) RETURNS varchar(1000) CHARSET utf8mb4
DETERMINISTIC
BEGIN
DECLARE sTemp VARCHAR(1000) default rootId;
DECLARE sTempChd VARCHAR(1000);
SET sTempChd =cast(rootId as CHAR);
WHILE sTempChd is not null do
if sTemp<>sTempChd then
SET sTemp = concat(sTemp,',',sTempChd);
END IF;
SELECT group_concat(id) INTO sTempChd FROM unify_space_database.t_space where FIND_IN_SET(pid,sTempChd);
END WHILE;
RETURN sTemp;
END
标签:rootId,SET,sTempChd,自定义,查询,sTemp,fid,END,节点 来源: https://blog.51cto.com/u_15155073/2695941