您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

mysql 树形结构查询(存储过程)_MySQL

2025/11/10 7:59:52发布8次查看
就用数据数据库表地址数据(中国地区) 来说吧(用windows 请使用 gbk !!)
可直接运行(去除注解)
存储过程:
delimiter//
dropprocedureifexists findlchild//
/*iid递归父节点,layer允许递归深度*/
createprocedurefindlchild(iidbigint(20),layerbigint(20))
 begin
/*创建接受查询的临时表*/
createtemporary tableifnotexiststmp_table(idbigint(20),namevarchar(50))engine=innodbdefaultcharset=utf8;
/*最高允许递归数*/
set@@max_sp_recursion_depth=99;
calliterative(iid,layer);/*核心数据收集*/
select*fromtmp_table;/*展现*/
droptemporary tableif exists tmp_table;/*删除临时表*/
  end;//
delimiter;
delimiter//
dropprocedureifexists iterative//
createprocedureiterative(iidbigint(20),layerbigint(20))
begin
declaretidbigint(20)default-1;
declaretnamevarchar(50)charactersetutf8;
/*游标定义*/
declarecur1cursorforselectid,namefromlocationwherefid=iid;
declarecontinuehandlerforsqlstate'02000'settid=null;
/*允许递归深度*/
 iflayer>0then
opencur1;
fetchcur1intotid,tname;
 while(tidisnotnull)
do
 /*核心数据收集*/
 insertintotmp_tablevalues(tid,tname);
 calliterative(tid,layer-1);
 fetchcur1intotid,tname;
 endwhile;
 endif;
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)
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product