标签:-- child mysq 查询 递归函数 exist weight into 实现
-- 向下递归函数 SELECT GROUP_CONCAT(‘‘‘‘, pk_dept , ‘‘‘‘) FROM rzzxdb.bi_dept WHERE FIND_IN_SET(fr_pk_dept,‘1070‘)>0;
结果:
利用find_in_set()函数和group_concat()函数实现递归查询:
DROP FUNCTION IF EXISTS queryChildrenAreaInfo; CREATE FUNCTION queryChildrenAreaInfo(areaId INT) -- 或者 areaId char 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;
调用方式:
SELECT * FROM t_areainfo WHERE FIND_IN_SET(id,queryChildrenAreaInfo(4));
DROP FUNCTION IF EXISTS queryChildrenAreaInfo1; CREATE FUNCTION queryChildrenAreaInfo1(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;
调用方式:
SELECT * from t_areainfo where FIND_IN_SET(id,queryChildrenAreaInfo1(7));
标签:-- child mysq 查询 递归函数 exist weight into 实现
原文地址:https://www.cnblogs.com/lizm166/p/10319277.html