您发布的查询缺少该
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可以返回表的全部内容。
我还添加了外部查询,以从结果集中过滤出根行,这在您的问题中没有提到,但已显示在您想要的结果中。
SQL小提琴示例
评论回应:
在提供的版本中,您确实可以获取的后代
id = 3,但不能以其
3为根。这是因为我们从绝对根开始。解决这个问题很容易,只需省略以下
startwith子句:
SELECt *FROM (SELECt connect_by_root(id) root_id, id, parent_id FROM test1ConNECT BY PRIOR id = parent_id)WHERe root_id <> id



