oracle中可以通过start with . . . connect by . . .子句来实现sql的层次查询.自从oracle 9i开始,可以通过 sys_connect_by_path
oracle中可以通过start with . . . connect by . . .子句来实现sql的层次查询.
自从oracle 9i开始,可以通过 sys_connect_by_path 函数实现将父节点到当前行内容以“path”或者层次元素列表的形式显示出来。
自从oracle 10g 中,还有其他更多关于层次查询的新特性 。例如,有的时候用户更关心的是每个层次分支中等级最低的内容。
那么你就可以利用伪列函数connect_by_isleaf来判断当前行是不是叶子。如果是叶子就会在伪列中显示“1”,
如果不是叶子而是一个分支(例如当前内容是其他行的父亲)就显示“0”。
在oracle 10g 之前的版本中,如果在你的树中出现了环状循环(如一个孩子节点引用一个父亲节点),
oracle 就会报出一个错误提示:“ ora-01436: connect by loop in user data”。如果不删掉对父亲的引用就无法执行查询操作。
而在 oracle 10g 中,只要指定“nocycle”就可以进行任意的查询操作。与这个关键字相关的还有一个伪列——connect_by_iscycle,
如果在当前行中引用了某个父亲节点的内容并在树中出现了循环,那么该行的伪列中就会显示“1”,否则就显示“0”。
the start with .. connect by clause can be used to select data that has a hierarchical relationship
(usually some sort of parent->child, boss->employee or thing->parts).
it is also being used when an sql execution plan is explained.
syntax:
select ... [start with initial-condition] connect by [nocycle] recurse-condition
level
with level it is possible to show the level in the hierarchical relation of all the data.
--oracle 9i
sys_connect_by_path
with sys_connect_by_path it is possible to show the entire path from the top level down to the 'actual' child.
--oracle 10g
connect_by_root
connect_by_root is a new operator that comes with oracle 10g and enhances the ability to perform hierarchical queries.
connect_by_is_leaf
connect_by_isleaf is a new operator that comes with oracle 10g and enhances the ability to perform hierarchical queries.
connect_by_iscycle
connect_by_is_cycle is a new operator that comes with oracle 10g and enhances the ability to perform hierarchical queries.
下面举例说明:
[例1]
创建一个部门表,这个表有4个字段,分别对应部门id,部门名称,,上级部门id ,本部门直属员工人数。
create table dep
(
depid number(10) not null,
depname varchar2(32),
upperdepid number(10),
numofemp number(10)
) ;
下面插入一些数据,结果如下:
现在根据“connect by”来实现树状查询:
结果如下:
下面计算dev center和test center部门的总人数:
结果如下: