只要你在11gR2或更高版本上,你可以使用recursive subquery factoring而不是connect by
分层语法。
如果你的表称为t
有:
CHILD_ID PARENT_ID CHILD_T
---------- ---------- -------
0 root
1 0 first
2 1 second
3 2 third
4 2 fourth
5 6 fifth
6 3 sixth
7 6 seventh
你可以这样做:
with r (child_id, child_title, id_path, title_path) as (
select child_id, child_title, to_clob(null), to_clob(null)
from t
where parent_id is null
union all
select t.child_id, t.child_title,
t.parent_id ||','|| r.id_path, r.child_title ||'|'|| r.title_path
from r
join t on t.parent_id = r.child_id
)
select child_id, id_path, title_path
from r
order by child_id;
CHILD_ID ID_PATH TITLE_PATH
---------- -------------------- ----------------------------------------
0
1 0, root|
2 1,0, first|root|
3 2,1,0, second|first|root|
4 2,1,0, second|first|root|
5 6,3,2,1,0, sixth|third|second|first|root|
6 3,2,1,0, third|second|first|root|
7 6,3,2,1,0, sixth|third|second|first|root|
锚构件转动路径转换的CLOB;递归成员将每个标题附加到CLOB,CLOB将其保留为该数据类型。
可以剪掉后面的逗号/条,或修改查询了一点,所以他们从来没有出现:
with r (parent_id, child_id, child_title, id_path, title_path) as (
select parent_id, child_id, child_title, to_clob(null), to_clob(null)
from t
where parent_id is null
union all
select t.parent_id, t.child_id, t.child_title,
t.parent_id || case when r.parent_id is not null then ',' end || r.id_path,
r.child_title || case when r.parent_id is not null then '|' end || r.title_path
from r
join t on t.parent_id = r.child_id
)
select child_id, id_path, title_path
from r
order by child_id;
CHILD_ID ID_PATH TITLE_PATH
---------- -------------------- ----------------------------------------
0
1 0 root
2 1,0 first|root
3 2,1,0 second|first|root
4 2,1,0 second|first|root
5 6,3,2,1,0 sixth|third|second|first|root
6 3,2,1,0 third|second|first|root
7 6,3,2,1,0 sixth|third|second|first|root
你的样本值没有表现出一个CLOB的需要,但在更多的数据相加到虚拟表显示生成的值可超过4K:
insert into t
select level + 7, level + 6, 'title'
from dual
connect by level <= 2000;
with r (...) -- as above
select max(length(id_path)), max(length(title_path))
from r;
MAX(LENGTH(ID_PATH)) MAX(LENGTH(TITLE_PATH))
-------------------- -----------------------
8920 12031
只是为了澄清。你的问题不是预期的结果,而是4k的限制? –
是的,我的问题是4k的限制。我能够使用CONNECT BY PRIOR获取路径。但结果预计会超过4k的限制。 – ujwal
我有一个备份方法来创建一个临时表结果集到一个clob,我不愿意做,因为主表预计会频繁更改,我需要关心所有的子节点,如果中间节点是除去。 – ujwal