您发布的查询缺少该from
子句,并在下划线下划线connect_by_root
,但我认为这些实际上并不是问题的根源。
以下查询为您提供所需的结果:
select * from (
select connect_by_root(id) root_id, id, parent_id
from test1
start with parent_id is null
connect by prior id = parent_id)
where root_id <> id
中心问题是您要指定一个特定的值开始,而不是指定一种方法来标识根行。更改id = 1
为parent_id is null
可以返回表的全部内容。
我还添加了外部查询,以从结果集中过滤出根行,这在您的问题中没有提到,但已显示在您想要的结果中。
评论回应:
在提供的版本中,您确实可以获取的后代id = 3
,但不能以其3
为根。这是因为我们从绝对根开始。解决这个问题很容易,只需省略以下start with
子句:
SELECT *
FROM
(SELECT connect_by_root(id) root_id,
id,
parent_id
FROM test1
CONNECT BY
PRIOR id = parent_id)
WHERE root_id <> id