oracle中 connect by prior 递归算法

有时候在界面常可以看到一种树形结构的案例:
  那么在数据库中是怎么设计的呢?
  给一个案例:
    
create table Employee
(

  parent_id int,--这个作为关联本身的父类节点
   child_id int, 
  name varchar2(20) 
)

insert into  employee values(1,2,'第2个');
insert into  employee values(1,3,'第3个');
insert into  employee values(2,4,'第4个');
insert into  employee values(2,5,'第5个');
insert into  employee values(3,6,'第6个');
insert into  employee values(3,7,'第7个');
insert into  employee values(4,8,'第8个');
insert into  employee values(4,9,'第9个');
insert into  employee values(5,10,'第10个');
insert into  employee values(5,11,'第11个');
insert into  employee values(8,12,'第12个');
insert into  employee values(8,13,'第13个');

这是一个有上面设计而得的二叉树

 


从网上得知Oracle中start with...connect by prior子句用法 connect by 是可以用做查询数结构,而其基本语法是:
select ... from tablename start with 条件1
connect by 条件2
where 条件3;(这个条件不能放在末尾,要放在表名之后,否则会报错)
所以
例:

(1)select * from employee start with child_id=5 connect by prior parent_id=child_id

(2)select * from employee start with child_id=2 connect by prior child_id=parent_id

结果(1)

结果(2)


     简单说来是将一个树状结构存储在一张表里,比如一个表中存在两个字段:
  child_id,parent_id那么通过表示每一条记录的parent是谁,就可以形成一个树状结构。
     用上述语法的查询可以取得这棵树的所有记录。
     其中:
     条件1 是根结点的限定语句,当然可以放宽限定条件,以取得多个根结点,实际就是多棵树。
     条件2 是连接条件,其中用PRIOR表示上一条记录,比如 CONNECT BY PRIOR child_id= parent_id 就是说上一条记录的org_id 是本条记录的parent_id,即本记录的父亲是上一条记录。
     这个prior靠近哪边就往哪边查,如第(1)种情况就是父类方向查,第(2)种情况就是向子类方向查
     条件3 是过滤条件,用于对返回的所有记录进行过滤。
  

     简单介绍如下:
     早扫描树结构表时,需要依此访问树结构的每个节点,一个节点只能访问一次,其访问的步骤如下:
     第一步:从根节点开始;
     第二步:访问该节点;
     第三步:判断该节点有无未被访问的子节点,若有,则转向它最左侧的未被访问的子节,并执行第二步,否则执行第四步;
     第四步:若该节点为根节点,则访问完毕,否则执行第五步;
     第五步:返回到该节点的父节点,并执行第三步骤。

     总之:扫描整个树结构的过程也即是二叉树的中序遍历树的过程。


原文地址:https://www.cnblogs.com/yaobolove/p/5804396.html