语法格式:
select [level], column, expr... from table
[where condition]
start with condition
connect by [prior column1= column2 |
column1 = prior column2];
层次查询是通过start with和connect by子句标识的:
1.其中level关键字是可选的,表示等级,1表示root,2表示root的child,其他相同的规则。
2.From之后可以是table,view但是只能是一个table。
3.Where条件限制了查询返回的行,但是不影响层次关系,属于将节点截断,但是这个被截断的节点的下层child不受影响。
4.Start with是表示开始节点,对于一个真实的层次关系,必须要有这个子句,但是不是必须的。
5.connect by prior是指定父子关系,其中prior的位置不一定要在connect by之后,对于一个真实的层次关系,这也是必须的。
示例:
在自连接中,数据量大的话会出现笛卡尔集的情况,为了避免这种情况的发生,就使用Oracle当中的层次查询
SQL> --通过表的别名,将同一张表视为多张表
SQL> select e.ename||'的老板是'||b.ename
2 from emp e,emp b
3 where e.mgr=b.empno;
结果:
那下面呢,我就这张图画一张树形关系图
SQL> --执行层次查询
SQL> select level,empno,ename,mgr
2 from emp
3 connect by prior empno=mgr
4 start with mgr is null
5 order by 1;
结果: