选择 CONNECT_BY_ROOT ID 作为 store_id,id 作为 current_id 来自商店 其中 ISACTIVE = 1 通过事先传输连接EXTSTOREID = ID;
查询解释?
首先,将所有 isactive=1 的行作为锚点进行递归。其他行的端点是 isactive=1 的行。
下一级 - 行,通过
transfertonextstoreid
链接到锚行。这样,我们就不会在递归中生成额外的行。
如果我们从相反的一侧去寻找根行,中间的步骤可能是多余的,并且必须将它们过滤掉。
step 1 row (25, 1, NULL) =output (25, 1, NULL)
step 2 row (20, 0, 25)->(25, 1, NULL) =output (20, 0, 25)
step 3 row (14, 0, 20)->(20, 0, 25) =output (14, 0, 25)
step 4 row (10, 0, 14)->(14, 0, 25) =output (10, 0, 25)
参见示例
with rec_cte as ( -- anchor - rows with isactive=1
select s.id, s.id as current_id,
s.isactive,
1 as reclevel
from store s
where isactive=1
union all
-- carrent_id is not changed, saved from anchor
select s.id, r.current_id as current_id,
s.isactive,
r.reclevel + 1
from rec_cte r
join store s on s.transfertonextstoreid = r.id
)
select *
from rec_cte
order by id, reclevel;
id | 当前_id | 处于活动状态 | 恢复水平 |
---|---|---|---|
12 | 12 | 1 | 1 |
25 | 25 | 1 | 1 |
38 | 38 | 1 | 1 |
60 | 60 | 1 | 1 |
77 | 77 | 1 | 1 |
120 | 120 | 1 | 1 |
11 | 12 | 0 | 2 |
20 | 25 | 0 | 2 |
54 | 77 | 0 | 2 |
101 | 120 | 0 | 2 |
14 | 25 | 0 | 3 |
37 | 77 | 0 | 3 |
99 | 120 | 0 | 3 |
10 | 25 | 0 | 4 |
40 | 120 | 0 | 4 |