MySQL遞迴查詢所有子節點,樹形結構查詢

2022-07-22 02:27:10 字數 2637 閱讀 8367

delimiter //

drop procedure if exists   findlchild//

/* iid 遞迴父節點 , layer 允許遞迴深度 */

create procedure findlchild(iid bigint(20),layer bigint(20))

begin

/*建立接受查詢的臨時表 */

create temporary  table if not exists tmp_table(id bigint(20),name varchar(50)) engine=innodb default charset=utf8;

/*最高允許遞迴數*/

set @@max_sp_recursion_depth = 99 ;

call iterative(iid,layer);/*核心資料收集*/

select * from tmp_table ;/* 展現 */

drop temporary  table if  exists   tmp_table ;/*刪除臨時表*/

end;//

delimiter ;

delimiter //

drop procedure if exists   iterative //

create procedure iterative(iid bigint(20),layer bigint(20))

begin

declare tid bigint(20) default -1 ;

declare tname varchar(50) character set utf8;

/* 游標定義 */

declare cur1 cursor for select id,name from location where fid=iid ;

declare continue handler for sqlstate '02000' set tid = null;

/* 允許遞迴深度 */

if layer>0 then

open cur1 ;

fetch cur1 into tid,tname ;

while ( tid is not null ) 

do/* 核心資料收集 */

insert into tmp_table values(tid,tname);

call iterative(tid,layer-1);

fetch cur1 into tid,tname ;

end while;

end if;

end;//

delimiter ;

delimiter //

drop procedure if exists   findlchild//

/* iid 遞迴父節點 , layer 允許遞迴深度 */

create procedure findlchild(iid bigint(20),layer bigint(20))

begin

/*建立接受查詢的臨時表 */

create temporary  table if not exists tmp_table(id bigint(20),name varchar(50)) engine=innodb default charset=utf8;

/*最高允許遞迴數*/

set @@max_sp_recursion_depth = 99 ;

call iterative(iid,layer);/*核心資料收集*/

select * from tmp_table ;/* 展現 */

drop temporary  table if  exists   tmp_table ;/*刪除臨時表*/

end;//

delimiter ;

delimiter //

drop procedure if exists   iterative //

create procedure iterative(iid bigint(20),layer bigint(20))

begin

declare tid bigint(20) default -1 ;

declare tname varchar(50) character set utf8;

/* 游標定義 */

declare cur1 cursor for select id,name from location where fid=iid ;

declare continue handler for sqlstate '02000' set tid = null;

/* 允許遞迴深度 */

if layer>0 then

open cur1 ;

fetch cur1 into tid,tname ;

while ( tid is not null ) 

do/* 核心資料收集 */

insert into tmp_table values(tid,tname);

call iterative(tid,layer-1);

fetch cur1 into tid,tname ;

end while;

end if;

end;//

delimiter ;

mysql 遞迴查詢選單節點的所有子節點

背景 專案中遇到乙個需求,要求查處選單節點的所有節點,在網上查了一下,大多數的方法用到了儲存過程,由於線上環境不能隨便新增儲存過程,因此在這裡採用類似遞迴的方法對選單的所有子節點進行查詢。準備 建立menu表 create table menu id int 11 not null auto inc...

mysql 遞迴查詢選單節點的所有子節點

建立menu表 create table menu id int 11 not null auto increment comment 選單id parent id int 11 default null comment 父節點id menu name varchar 128 default nul...

mysql 樹表查詢所有子節點

create table ifnot exists sys dept id bigint 20 not null auto increment comment 部門id parent id bigint 20 default 0 comment 父部門id ancestors varchar 50 ...