Oracle SQL递归查询以查找第一级的父级

时间:2013-09-11 13:01:52

标签: sql oracle recursion

假设我有桌面服务:

     Name      | ID | PARENT_ID | LEVEL | 
------------------------------------------- 
 s1            | 1  | null      | 0     | 
 s2            | 2  | 1         | 1     | 
 s3            | 3  | 1         | 2     |      
 s4            | 4  | 2         | 2     | 
 s5            | 5  | 3         | 3     | 
 s6            | 6  | 4         | 3     |

我希望获得s6(id = 6)的1级父级,它应该返回s2,有没有办法进行递归查询,直到达到某个级别?

2 个答案:

答案 0 :(得分:4)

你可以上去树而不是下去 - 从leaf(id = 6)到root(在这个反向情况下本身就是一个叶子,connect_by_isleaf = 1),并取一个“父” “使用prior运算符的那片叶子。

upd :误解了您对LEVEL的要求(在Oracle分层查询中,它是指定行的层次深度的动态伪列)。如果您希望将结果集限制为具有自定义预填充LEVEL列的特定值的行,则只需将其添加到where条件。

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE t
    ("NAME" varchar2(2), "ID" int, "PARENT_ID" int, "LVL" int)
;

INSERT ALL 
    INTO t ("NAME", "ID", "PARENT_ID", "LVL")
         VALUES ('s1', 1, NULL, 0)
    INTO t ("NAME", "ID", "PARENT_ID", "LVL")
         VALUES ('s2', 2, 1, 1)
    INTO t ("NAME", "ID", "PARENT_ID", "LVL")
         VALUES ('s3', 3, 1, 2)
    INTO t ("NAME", "ID", "PARENT_ID", "LVL")
         VALUES ('s4', 4, 2, 2)
    INTO t ("NAME", "ID", "PARENT_ID", "LVL")
         VALUES ('s5', 5, 3, 3)
    INTO t ("NAME", "ID", "PARENT_ID", "LVL")
         VALUES ('s6', 6, 4, 3)
SELECT * FROM dual
;

查询1

select id as id, name as name from t
where lvl = 1
connect by  id = prior parent_id
  start with id = 6

<强> Results

| ID | NAME |
|----|------|
|  2 |   s2 |

答案 1 :(得分:3)

这可以通过分层查询实现:

create table tq84_h (
  id number,
  parent_id number,
  level_    number
);

insert into tq84_h values (1, null, 0);
insert into tq84_h values (2, 1   , 1);
insert into tq84_h values (3, 1   , 2);
insert into tq84_h values (4, 2   , 2);
insert into tq84_h values (5, 3   , 3);
insert into tq84_h values (6, 4   , 3);

select 
  parent_id
from
  tq84_h
where
  level_ = 2
start with
  id = 6
connect by
  prior parent_id = id and
  level_>1
;