递归查询相关的知识,希望对你有一定的参考价值。
方法一:(普通函数形式)
说明: 利用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 ;
方法二:(mysql 8 WITH RECURSIVE
函数)
原数据
一: 向下查询
with recursive temp as(
select * from user_test where id = 1
union all
select u.* from user_test u,temp t where t.id = u.pri
)
select * from temp;
二:向上查询
with recursive temp as(
select * from user_test where id = 5
union all
select u.* from user_test u,temp t where t.pri = u.id
)
select * from temp;