`
zyn010101
  • 浏览: 319884 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

MYSQL树状查询

阅读更多



 oracle中可以采用connect by 来进行树状查询,在MYSQL中却没有提供该功能,但是,使用存贮过程我们也可以实现该查询。

创建一张表 fd_id varchar(50)--主键,fd_name varchar(50),fd_parentid varchar(20);

 

创建存贮过程:

 

drop procedure if exists   findLChild;
/* iid 递归父节点 , layer 允许递归深度 */

CREATE PROCEDURE findLChild(iid varchar(50),layer bigint(20))
BEGIN
    /*创建接受查询的临时表 */
    create temporary  table if not exists tmp_table(id varchar(50),name varchar(50)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    /*最高允许递归数*/
    SET @@max_sp_recursion_depth = 10 ;
     call iterative(iid,layer);/*核心数据收集*/
    select * from tmp_table ;/* 展现 */
    drop temporary  table if  exists   tmp_table ;/*删除临时表*/
   END;


drop procedure if exists   iterative ;
CREATE PROCEDURE iterative(iid varchar(50),layer bigint(20))
    BEGIN
  	 declare tid varchar(50) default iid ;
         declare tname varchar(50) character set utf8;

         /* 游标定义 */
         declare cur1 CURSOR FOR select fd_id,fd_name from sys_org_element where fd_parentid=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;

 

调用存贮过程:call findLChild('12d8385f65a85c497d232ef4294ac737',5);

结果

  • 大小: 68.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics