mysql如何实现递归向上查询和递归向下查询所有数据

2024年10月02日 建站教程

如何利用mysql​语法实现递归向上查询和递归向下查询所有数据,下面给介绍一下2种不同方法的书写。

向上递归方法:

DROP FUNCTION IF EXISTS queryChildrenData;
DELIMITER;;
CREATE FUNCTION queryChildrenData(areaId INT)
RETURNS VARCHAR(4000)
BEGIN
DECLARE sTemp VARCHAR(4000);
DECLARE sTempChd VARCHAR(4000);
SET sTemp='$';
SET sTempChd = CAST(areaId AS CHAR);
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT parentId INTO sTempChd FROM t_areainfo WHERE id = sTempChd;
WHILE sTempChd <> 0 DO
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT parentId INTO sTempChd FROM t_areainfo WHERE id = sTempChd;
END WHILE;
RETURN sTemp;
END
;;
DELIMITER ;

调用方法:

SELECT * from t_areainfo where FIND_IN_SET(id,queryChildrenData(查当前id向上的所有数据));

向下递归方法:

DROP FUNCTION IF EXISTS queryChildrenData2;
DELIMITER ;;
CREATE FUNCTION queryChildrenData2(areaId INT)
RETURNS VARCHAR(4000)
BEGIN
DECLARE sTemp VARCHAR(4000);
DECLARE sTempChd VARCHAR(4000);
SET sTemp='$';
SET sTempChd = CAST(areaId AS CHAR);
WHILE sTempChd IS NOT NULL DO
SET sTemp= CONCAT(sTemp,',',sTempChd);
SELECT GROUP_CONCAT(id) INTO sTempChd FROM t_areainfo WHERE FIND_IN_SET(parentId,sTempChd)>0;
END WHILE;
RETURN sTemp;
END
;;
DELIMITER ;

调用方法:

SELECT * FROM t_areainfo WHERE FIND_IN_SET(id,queryChildrenData(查当前id向下的所有数据));

本文链接:http://so.lmcjl.com/news/14435/

展开阅读全文
相关内容