分层查询中的oracle祖先

时间:2013-07-02 10:42:34

标签: sql oracle hierarchy

给出包含数据的表 T_Person(名称,父)

+--------+--------+
| name   | parent |
+--------+--------+
| john   | peter  |
| peter  | ronald |
| ronald | george |
| george |        |
+--------+--------+

可以使用此查询找到关系:

select name, parent, LEVEL
from T_Person
connect by prior name = parent
start with parent is null;

结果将是:

+--------+--------+-------+
| name   | parent | LEVEL |
+--------+--------+-------+
| john   | peter  | 4     |
| peter  | ronald | 3     |
| ronald | george | 2     |
| george |        | 1     |
+--------+--------+-------+

到目前为止这很好。但我希望得到一个包含所有这种看法的关系的结果:

+--------+--------+----------------+
| name   | parent | relation_level |
+--------+--------+----------------+
| john   | peter  | 1              |
| peter  | ronald | 1              |
| ronald | george | 1              |
| john   | ronald | 2              |
| peter  | george | 2              |
| john   | george | 3              |
+--------+--------+----------------+

(relation_level:1 =父亲,2 =祖父,3 =祖父等等)

除了在每个关系级别的整个表中选择之外,是否有快速的oracle方式来接收此结果?

2 个答案:

答案 0 :(得分:3)

或者您可以删除start with clause

SELECT name, ancestor AS parent, l
FROM
(
  SELECT name, parent, LEVEL-1 l, connect_by_root name ancestor
    FROM T_Person
 CONNECT BY PRIOR name = parent
) t
WHERE t.ancestor <> t.name

Here is a sqlfiddle demo

答案 1 :(得分:2)

create table ancestor (name varchar2(200), parent varchar2(200));

insert into ancestor values ('john','peter');
insert into ancestor values ('peter','ronald');
insert into ancestor values ('ronald','george');
insert into ancestor values ('george',null);

 select  name,parent,relation_level from 
(

 SELECT CONNECT_BY_ROOT name name, parent,level relation_level
 FROM ancestor
 CONNECT BY name = PRIOR parent
  START WITH name IN (SELECT name FROM ancestor)
 )
where parent is not null;

SQLFIDDLE