mysql 樹操作函式,取子節點,取父節點
取子節點
DROP FUNCTION IF EXISTS FUN_GET_CHILD_LIST;
CREATE FUNCTION FUN_GET_CHILD_LIST (ROOT_ID INT)
RETURNS varchar(1000)
BEGIN
DECLARE sTemp VARCHAR (1000) ;
DECLARE sTempChd VARCHAR (1000) ;
SET sTemp = '$' ;
SET sTempChd = CAST(ROOT_ID AS CHAR) ;
WHILE
sTempChd IS NOT NULL DO SET sTemp = CONCAT(sTemp, ',', sTempChd) ;
SELECT
GROUP_CONCAT(id) INTO sTempChd
FROM
uc_module
WHERE FIND_IN_SET(parent_id, sTempChd) > 0 ;
END WHILE ;
RETURN sTemp ;
END;
select * from uc_module where FIND_IN_SET(id,FUN_GET_CHILD_LIST(1));
取父節點
DROP FUNCTION IF EXISTS FUN_GET_PARENT_LIST;
CREATE FUNCTION `FUN_GET_PARENT_LIST`(leafId varchar(20))
RETURNS varchar(1000)
BEGIN
DECLARE fid varchar(20) default '';
DECLARE str varchar(1000) default leafId;
WHILE leafId is not null do
SET fid =(SELECT parent_id FROM uc_module WHERE id = leafId);
IF fid is not null THEN
SET str = concat(str, ',', fid);
SET leafId = fid;
ELSE
SET leafId = fid;
END IF;
END WHILE;
return str;
END
select*from uc_module where FIND_IN_SET(id,FUN_GET_PARENT_LIST(17));