1

假设我有餐桌服务:

     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     |

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

4

2 回答 2

4

您可以向上而不是向下 - 从叶子 (id = 6) 到根(在这种相反的情况下,它本身就是叶子,connect_by_isleaf = 1),并使用prior运算符获取该叶子的“父”。

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

SQL小提琴

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

结果

| ID | NAME |
|----|------|
|  2 |   s2 |
于 2013-09-11T13:15:23.977 回答
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
;
于 2013-09-11T13:16:02.507 回答