从 child 到 ORACLE 12c 中的曾曾祖父列表的查询

query from the child to the great great grandfather list in ORACLE 12c

我需要有关 SQL 查询的帮助。 我有这个 table:

ITEM     PARENT
1          NULL
2           1
3           2
4           2
5           3
6           5
7           5
8           4
9           8
10          1
11          10
12          10
13          8       

选择一个项目,我需要以下结果:

已选第 9 项:家庭列表:8,4,2,1

您可以使用 START WITHCONNECT BY

解决此问题

Oracle documentation for Hierarchical Queries

您的 SQL 如下所示

SELECT item 
  FROM t START WITH item = 9 
CONNECT BY PRIOR parent = item

具体来说 9

SELECT parent
FROM yourtable 
WHERE item = 9
UNION ALL
SELECT parent
FROM yourtable 
WHERE item IN (SELECT parent
                FROM yourtable y2
                WHERE item = 9
                AND item = y2.item)
UNION ALL
SELECT parent
FROM yourtable 
WHERE item IN (SELECT parent
               FROM yourtable 
               WHERE item IN (SELECT parent
                              FROM yourtable y2
                              WHERE item = 9
                              AND item = y2.item))
UNION ALL
SELECT parent
FROM yourtable 
WHERE item IN (SELECT parent
               FROM yourtable 
               WHERE item IN (SELECT parent
                              FROM yourtable 
                              WHERE item IN (SELECT parent
                                             FROM yourtable y2
                                             WHERE item = 9
                                             AND item = y2.item)))

使用参数@ITEM

SELECT parent
FROM yourtable 
WHERE item = @ITEM
UNION ALL
SELECT parent
FROM yourtable 
WHERE item IN (SELECT parent
                FROM yourtable y2
                WHERE item = @ITEM
                AND item = y2.item)
UNION ALL
SELECT parent
FROM yourtable 
WHERE item IN (SELECT parent
               FROM yourtable 
               WHERE item IN (SELECT parent
                              FROM yourtable y2
                              WHERE item = @ITEM
                              AND item = y2.item))
UNION ALL
SELECT parent
FROM yourtable 
WHERE item IN (SELECT parent
               FROM yourtable 
               WHERE item IN (SELECT parent
                              FROM yourtable 
                              WHERE item IN (SELECT parent
                                             FROM yourtable y2
                                             WHERE item = @ITEM
                                             AND item = y2.item)))

输出

PARENT
8
4
2
1

SQL Fiddle: http://sqlfiddle.com/#!4/97af9/11/0