只要你在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