读书人

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

发布时间: 2012-09-09 09:27:54 作者: rapoo

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

就用数据数据库表地址数据(中国地区)来说吧(用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)

?

?

?

读书人网 >Mysql

热点推荐