sql - Oracle中的递归查询,直到层次结构中的父级满足条件?
问题描述
我有一个如下表:
ID PARENT_ID VALUE_ID
1 NULL 100
2 1 NULL
3 2 200
4 3 NULL
5 1 300
6 2 NULL
7 6 400
8 7 500
我希望能够获取每个 ID 及其对应的 VALUE_ID。我想这样做,如果一行的 VALUE_ID 为 NULL,它“继承”层次结构中它上面的第一个父级的 VALUE_ID,它的 VALUE_ID 为 NOT NULL。所以这将是查询结果:
ID VALUE_ID
1 100
2 100 // -> inherits the value from PARENT_ID = 1;
3 200
4 200 // -> inherits the value from PARENT_ID = 3;
5 300
6 100 // -> inherits the value from ID = 1, because the PARENT_ID = 2 also has VALUE_ID as NULL, so it goes deeper in the hierarchy;
7 400
8 500
这样的事情可以只用一个递归或分层查询来完成吗?或者一般不用程序就可以完成,也许?使用 CTE 还是 CONNECT BY 子句?
解决方案
您可以为此使用递归 CTE:
with cte(id, value_id, parent_value_id) as (
select id, value_id, value_id as parent_value_id
from t
where value_id is not null
union all
select t.id, t.value_id, cte.parent_value_id
from cte join
t
on t.parent_id = cte.id
where t.value_id is null
)
select *
from cte
order by id;
这是一个 db<>fiddle。