Oracle:递归自引用连接与第n级记录

时间:2015-06-24 07:00:00

标签: sql oracle self-referencing-table

我有这样的自我参照表:

id   |level | parent_id
----------------------
1    |1     |null
2    |1     |null
3    |2     |1
4    |2     |1
5    |2     |2
6    |3     |5
7    |3     |3
8    |4     |7
9    |4     |6
------------------------

我在结果中需要第n级父级。例如第二级父母

id   |level | parent_id| second_level_parent_id
------------------------------------------------
1    |1     |null      |null
2    |1     |null      |null
3    |2     |1         |null
4    |2     |1         |null
5    |2     |2         |null
6    |3     |5         |5
7    |3     |3         |3
8    |4     |7         |3
9    |4     |6         |5
-------------------------------------------------

1 个答案:

答案 0 :(得分:1)

这适合我。

SELECT m.*,
  CONNECT_BY_ROOT id AS second_level_parent_id
FROM my_table m
WHERE CONNECT_BY_ROOT level =2
  CONNECT BY prior id    = parent_id;

感谢@JozefDúc