MySql 递归查询
一、递归语句
-- 向下递归函数 SELECT GROUP_CONCAT('''', pk_dept , '''') FROM rzzxdb.bi_dept WHERE FIND_IN_SET(fr_pk_dept,'1070')>0;
结果:
设置某个部门下的所有子部门为无效:
update bi_dept set zt ='0' WHERE FIND_IN_SET(fr_pk_dept,'部门ID')>0;
二、自定义递归函数
利用find_in_set()函数和group_concat()函数实现递归查询:
1,向下递归:
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));
2,向上递归:
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));
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/4993.html