該查詢給所有需要的信息:
select id_value, --parent_id_value piv, description, level tlvl,
sys_connect_by_path(description, '/') tpath
from hd where connect_by_isleaf = 1
start with parent_id_value not in (select id_value from hd)
connect by parent_id_value = prior id_value
結果
id_value tpath
-------- ---------------------------------------------------------------
40 /Top hierarchy/Other sub hierarchy/Rookie hierarchy
42 /Top hierarchy/Other sub hierarchy/Bottom level
1000 /Top hierarchy/Sub hierarchy
現在,如果我們假設最大層次結構深度爲3,則此查詢會將子層次結構置於單獨的列中。
with leaves as (
select id_value, parent_id_value piv, description, level tlvl,
sys_connect_by_path(rpad(description, 20), '/') tpath
from hd where connect_by_isleaf = 1
start with parent_id_value not in (select id_value from hd)
connect by parent_id_value = prior id_value)
select id_value,
substr(tpath, 2*20 + 4, 20) l3,
substr(tpath, 1*20 + 3, 20) l2,
substr(tpath, 0*20 + 2, 20) l1
from leaves
=====================================================================
id_value L3 L2 L1
40 Rookie hierarchy Other sub hierarchy Top hierarchy
42 Bottom level Other sub hierarchy Top hierarchy
1000 Sub hierarchy Top hierarchy
如果描述長度> 20,則將此值更改爲字段列長度。
這也可以很容易地在PL/SQL中動態完成,例如,通過首先計算深度,通過execute immediate
創建具有適當列數的表並將層次結構放入右列。
使用SELECT與PIVOT查詢,它將解決您的問題。 – Rigel1121 2015-02-12 05:51:33
@ Rigel1121,它不足以遞歸地找到父母。 – dmvianna 2015-02-12 05:54:23
層次結構有深度限制? – danihp 2015-02-12 12:59:50