您可以向上而不是向下 - 从叶子 (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 |