分层查询 - Oracle

时间:2015-12-03 13:10:10

标签: oracle hierarchical-data recursive-query connect-by

我有一个包含许多项目ID的表,对于每个项目,我都有如下的层次结构。

enter image description here

我的输入是风险ID。如何获得输入风险ID的顶级父级。

如果我将25作为输入,我应该得到23作为输出。我可以实现这一点。

1 个答案:

答案 0 :(得分:0)

从所需的行开始并上升到根目录:

SELECT RiskID,
FROM   PROJECT_RISKS
WHERE  CONNECT_BY_ISLEAF = 1
START WITH
       RiskID    = 25
CONNECT BY
       PRIOR Link2 = Link1
AND    PRIOR ProjectID = ProjectID;

从根开始并下降到所需的行:

SELECT  CONNECT_BY_ROOT( RiskID ) AS RiskID
FROM    Project_Risks
WHERE   RiskID    = 25
START WITH
        link2     IS NULL
CONNECT BY
       PRIOR Link1 = Link2
AND    PRIOR ProjectID = ProjectID;

两者都会给出相同的答案。