Oracle递归START WITH...CONNECT BY PRIOR子句用法


connect by 是结构化查询中用到的,其基本语法是:
select ... from tablename start with cond1
connect by cond2
where cond3;

例:

select * from class
start with parentid = 27362
Connect by prior id = parentid

简单说来是将一个树状结构存储在一张表里,比如一个表中存在两个字段:
id,parentid那么通过表示每一条记录的parent是谁,就可以形成一个树状结构。
用上述语法的查询可以取得这棵树的所有记录。
其中COND1是根结点的限定语句,当然可以放宽限定条件,以取得多个根结点,实际就是多棵树。
COND2是连接条件,其中用PRIOR表示上一条记录,比如 CONNECT BY PRIOR ID=PRAENTID就是说上一条记录的ID是本条记录的PRAENTID,即本记录的父亲是上一条记录。
COND3是过滤条件,用于对返回的所有记录进行过滤。

注意: 第一句会比第二句多一条,因为第二句是从parentid等于此值的节点往下找,不包括id等于此值的节点
select * from Class
start with Id = '000500010003'
Connect by prior id = parentid
--n+1 rows

select * from Class
start with parentid = '000500010003'
Connect by prior id = parentid
--n rows

工作实例:

select distinct * from usergroup b,groupinfo t
where b.groupid=t.member and t.type = 2
start with t.groupid='oa_customerSrv'
connect by prior t.member=t.groupid

相关内容

    暂无相关文章