mysql 父子节点查询

本文介绍了如何在SQL中创建函数GetChilds和GetParents,分别实现依据父ID查询子节点和子节点查询其父ID的功能。通过示例展示了如何使用这些函数操作表格table,涉及递归查询和find_in_set函数的应用。
摘要由CSDN通过智能技术生成

父子节点查询

table需要改名字
表结构
table (Id int,Name varchar(100),ParentId int)

依据父查子

drop function if exists GetChilds;
create function GetChilds(rootid int)
returns varchar(1000)
 
begin 
	declare stmp varchar(1000);
	declare stmpchild  varchar(1000);
	declare tid  int ;
	set stmp = ''; -- $
	set stmpchild = cast(rootid as char);
	
	while stmpchild is not null do 
		select id into tid from table where id = rootid;
		if tid > -1 then
				set stmp = concat(stmp,',',stmpchild);
					select group_concat(id order by id asc separator ',') into stmpchild from table  where find_in_set(ParentId,stmpchild);
				else 
					return SUBSTR(stmp,2); -- stmp
		end if;
	end while ;
	return substr(stmp,2); -- stmp 
end 

SELECT getchilds(1441);
SELECT getchilds(1471);
SELECT getchilds(10000000000);
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

查找字符在集合中的位置

select find_in_set('a','a,b,c,d'); -- 1
select find_in_set('c','a,b,c,d'); -- 3 
select find_in_set('x','a,b,c,d');-- 0 
select find_in_set('x','');-- 0
select find_in_set('x',null);-- Null

依据子查父

drop function if exists GetParents;
create function GetParents(rootid int)
returns varchar(1000)
 
begin 
	declare stmp varchar(1000);
	declare stmpparent  varchar(1000);
	declare tid  int ;
	set stmp = ''; -- $
	set stmpparent = cast(rootid as char);
	
	while stmpparent is not null do 
		select ParentId into tid from table where id = rootid;
		if tid > -1 then
				set stmp = concat(stmp,',',stmpparent);
					select group_concat(ParentId) into stmpparent from table where find_in_set(id,stmpparent)>0 and ParentId>0;
				else 
					return substr(stmp,2); -- stmp
		end if;
	end while ;
	return substr(stmp,2); -- stmp 
end 

SELECT GetParents(1471);
SELECT GetParents(1441);
SELECT GetParents(14711471);
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值