mysql 樹形結構查詢(儲存過程)

2021-08-29 17:06:57 字數 2657 閱讀 6308

就用資料資料庫表位址資料(中國地區) 來說吧(用windows 請使用 gbk !!)

可直接執行(去除註解)

儲存過程:

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> call findlchild(1,1)

+------+------------------+

| id   | name             |

+------+------------------+

|    2 | 北京             |

|    4 | 上海             |

|    6 | 香港特別行政區   |

|    8 | 澳門特別行政區   |

|   10 | 河北             |

|   23 | 山西             |

|   35 | 遼寧             |

|   50 | 吉林             |

|   60 | 黑龍江           |

|   74 | 江蘇             |

|   88 | 浙江             |

|  101 | 安徽             |

|  119 | 福建             |

|  129 | 江西             |

|  142 | 山東             |

|  160 | 河南             |

|  179 | 湖北             |

|  198 | 湖南             |

|  213 | 廣東             |

|  235 | 甘肅             |

|  250 | 四川             |

|  272 | 貴州             |

|  282 | 海南             |

|  301 | 雲南             |

|  318 | 青海             |

|  327 | 陝西             |

|  348 | 廣西壯族自治區   |

|  363 | **自治區       |

|  371 | 寧夏回族自治區   |

|  377 | 新疆維吾爾自治區 |

|  400 | 內蒙古自治區     |

|  413 | 台灣省           |

+------+------------------+

32 rows in set (0.02 sec)

sql 儲存過程 層次 樹形結構

用sql儲存過程生成樹形結構資料表。建立表 create table table newsclass newsclassname varchar 50 newsclassid int,newsclassparentid int insert into table newsclass select 頂...

mysql樹形結構查詢子節點

需求 在樹形的節點關係下,比如選單樹或者檔案目錄樹,要想獲取某個節點的所有子節點,或者所有父類節點,在知道節點樹最大層級的情況下,可以直接通過一條sql直接查詢實現 表結構 id,parent id eg 已知節點樹深度不超過10,查詢id 100010的節點的所有子節點 select org.id...

MySQL儲存過程,樹狀結構資料查詢

1.根據父級節點id查詢其所有的子級節點id,查詢結果中包含當前傳入的父級節點id值 根據傳入的父級id查詢所有子節點的id tablename 表名 idkey 節點標識 pidkey 父節點標識 pid 父節點id值 呼叫示例 call get child nodes org id pid 21...