Oracle数据库递归

时间:2014-05-12 06:34:34

标签: sql oracle hierarchical-data recursive-query

我有oracle数据库和table table_test:

id | p_id
---------
1  | null
2  | 1
3  | 2
4  | 1
5  | 3
6  | 4
7  | 3
8  | 5
9  | 6
10 | 7

我需要获取id = x?的所有层次结构ID。 结果应如下:

x? = 1 --> 1
x? = 2 --> 2,1
x? = 3 --> 3,2,1
x? = 4 --> 4,1
x? = 5 --> 5,3,2,1
x? = 6 --> 6,4,1
x? = 7 --> 7,3,2,1
x? = 8 --> 8,5,3,2,1
x? = 9 --> 9,6,4,1
x? = 10 --> 10,7,3,2,1

我应该使用什么SQL来获得这些结果?

非常感谢

1 个答案:

答案 0 :(得分:2)

谢谢大家,我得到了解决方案:

在ORACLE SQL中:

SELECT T.*
FROM table_test T
START WITH T.ID =X?
CONNECT BY PRIOR T.P_ID = T.ID

IN H2& SQLServer SQL:

WITH LINK(ID, PARENT_ID) AS (
SELECT ID, PARENT_ID
FROM TABLE_TEST 
WHERE ID = X?
UNION ALL
SELECT TABLE_TEST.ID,  TABLE_TEST.PARENT_ID
FROM LINK 
INNER JOIN TABLE_TEST ON LINK.PARENT_ID = TABLE_TEST.ID)

SELECT *
FROM LINK 
ORDER BY ID;