mysql分层的其他几种方式实现

本文介绍了两种MySQL分层查询的实现方法:一是通过SQL语句递归查询父节点,适用于固定层级;二是利用存储过程与临时表递归查询,适合多层结构,但受限于max_sp_recursion_depth参数。
摘要由CSDN通过智能技术生成

接一篇mysql分层方式的实现:https://blog.csdn.net/weixin_41561946/article/details/107132338

分层实现方式

方式一:SQL语句方式
select id,nodename,pid
,(select pid from treenodes where id=t.pid) parentid2
,(select pid from treenodes where id=(select pid from treenodes where id=t.pid)) parentid3
,(select pid from treenodes where id=(select pid from treenodes where id=(select pid from treenodes where id=t.pid))) parentid4
from treenodes t

在这里插入图片描述
方式二:存储过程+临时表

create PROCEDURE test(in rootid int,in ndepth int)
begin
			declare v_done int default 0;
			declare v_id int;
			declare cur1 cursor for select id from treenodes where pid=rootid;
			declare continue handler for not found set v_done=1;
			
			insert into tmplist value (null,rootid,ndepth);
			
			open cur1;
			fetch cur1 into v_id;
			while v_done=0 do
				call test(v_id,ndepth+1);
			end while ;
			close cur1;		

end;
create procedure showchildlist(in rootid int)
begin
	create temporary table if not exists tmplist(sno int primary key auto_increment,id int,depth int);
    delete from tmplist;
	call test(rootid,0);
	select a.*,b.* from tmplist a,treenodes b where a.id=b.id order by a.sno;
end

call showchildlist(6);

总结:

1、对于只有固定几层的来讲,第一种实现方式是通用的
2、对于只有多层的情况,第二种方式比较适合,但是受max_sp_recursion_depth=255参数的限制,最大为255层,但对第二种方式,测试表中只有20条记录,没有查询出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值