说明: 利用find_in_set()函数和group_concat()函数实现递归查询
一:向下查询:
DROPFUNCTION IF EXISTS testHS;
DELIMITER ;;
CREATE FUNCTION testHS(testId INT)
RETURNS VARCHAR(4000)
BEGIN
DECLARE sTemp VARCHAR(4000);
DECLARE sTempChd VARCHAR(4000);
SET sTemp='$';
SET sTempChd = CAST(testId AS CHAR);
WHILE sTempChd IS NOT NULL DO
SET sTemp= CONCAT(sTemp,',',sTempChd);
SELECT GROUP_CONCAT(id) INTO sTempChd FROM testInfo WHERE FIND_IN_SET(parentId,sTempChd)>0;
END WHILE;
RETURN sTemp;
END;;
DELIMITER ;
二:向上查询
DROP FUNCTION IF EXISTS testHS;
DELIMITER;;
CREATE FUNCTION testHS(testId VARCHAR(20))
RETURNS VARCHAR(4000)
BEGIN
DECLARE sTemp VARCHAR(4000);
DECLARE sTempChd VARCHAR(4000);
SET sTemp='$';
SET sTempChd = CAST(testId AS CHAR);
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT parentId INTO sTempChd FROM testInfo WHERE id = sTempChd;
WHILE sTempChd <> 0 DO
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT parentId INTO sTempChd FROM testInfo WHERE id = sTempChd;
END WHILE;
RETURN sTemp;
END;;
DELIMITER ;
|