查询从孩子到ORACLE 12c的曾祖父名单

时间:2015-06-03 10:27:36

标签: sql oracle parent-child hierarchy oracle12c

我需要SQL查询的帮助。 我有这张桌子:

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

2 个答案:

答案 0 :(得分:1)

您可以使用START WITHCONNECT BY

解决此问题

Oracle documentation for Hierarchical Queries

您的案例中的SQL将如下所示

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

答案 1 :(得分:0)

具体为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小提琴:http://sqlfiddle.com/#!4/97af9/11/0