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

接一篇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条记录,没有查询出结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值