oracle层次查询

.oracle层次查询(connect  by)
oracle的emp表中包含了一列mgr指出谁是雇员的经理,由于经理也是雇员,所以经理的信息也存储在emp表中。这样emp表就是一个自引用表,表中的mgr列是一个自引用列,它指向emp表中的empno列,mgr表示一个员工的管理者,
select   empno,mgr,ename,sal  from emp;
可以看到,要想从这些数据中提取出雇员和管理者的关系,可以使用connect  by和start  with字句。
语法:
select  [level],column,expression,.....
from table  where where_clause
start with start_condition connect by prior prior_condition
其中各参数的含义:
level:表示一个伪列,代表树的第几层
start_condition:定义了层次化查询的起点,当编写层次化查询时必须指定start with字句。
prior_condition:定义了父行和子行之间的关系,当编写层次化查询时必须定义connect  by  prior字句。
eg1:
select  empno,mgr,ename from  emp start with ename='king' connect by prior empno='mgr',结果集中mgr为空的就是根节点。
start with 指明从根节点king开始查询,使用connect by prior 让子节点的mgr指向父节点的empno。
eg2:使用伪列level
level是存在于oracle所执行的所有查询中的伪列,他是一个数值,可以指出节点在树中所处的层次,在层次化查询中,level值会将起始的根节点作为层次1,下面这个查询使用伪列level显示节点在树中的层次:
SQL>select  level,empno,mgr,ename  from emp start with ename='KING'  connect  by prior empno=mgr order by level;
上面的例子中增加了一列level,用于显示每个雇员在树中所处的层次。对根节点king来说,level返回1,根节点的子节点返回2,以此类推。
eg3:格式化层次查询结果
select level,lpad('    ',4*level-1)||ename from emp start with ename='King' connect by prior empno=mgr level lpad('    ',4*level-1)||ename
eg4:从非根节点开始遍历
select level,lpad('    ',4*level-1)||ename  from emp start with ename='Jones' connect by prior empno=mgr;这个查询从Jones开始查询
eg5:在start with 字句中使用子查询
select level,lpad('    ',4*level-1)||ename  from  emp start  with empno=(
select empno from emp where ename='Blake')
connect by prior empno=mgr
eg6:从下向上遍历树
select level,lpad('    ',4*level-1)||ename from emp start with ename='King'  connect by prior empno=mgr;
eg7:从层次化查询中删除节点和分支
select level,lpad('    ',4*level-1)||ename from emp   where ename!='Jones'  connect  by  prior  empno=mgr

猜你喜欢

转载自xiaoyaya751.iteye.com/blog/2215188