MySql 递归查询详解数据库

MySql 递归查询

一、递归语句

-- 向下递归函数 
SELECT GROUP_CONCAT('''', pk_dept , '''')  FROM rzzxdb.bi_dept WHERE FIND_IN_SET(fr_pk_dept,'1070')>0;

结果:

MySql 递归查询详解数据库

设置某个部门下的所有子部门为无效:

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/tech/database/4993.html

(0)
上一篇 2021年7月16日 23:23
下一篇 2021年7月16日 23:23

相关推荐

发表回复

登录后才能评论

WordPress 数据库错误: [Duplicate entry '80-d16c1647a53da3ad6bbb3d1108156ba7' for key 'task_id_source_url_key']
insert into wp_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(80,'https://pythonjishu.com/robotic-process-automation/','d16c1647a53da3ad6bbb3d1108156ba7',1735011725,0,0)