oracle表分层,sql – 对非分层数据的Oracle分层查询
我將一個(gè)Oracle表中的數(shù)據(jù)組織成可以包含循環(huán)的圖(參見示例).
CREATE TABLE T (parent INTEGER,child INTEGER)
AS select 1 parent,2 child from dual
union all select 1 parent,8 child from dual
union all select 2 parent,3 child from dual
union all select 2 parent,4 child from dual
union all select 2 parent,8 child from dual
union all select 3 parent,4 child from dual
union all select 3 parent,6 child from dual
union all select 4 parent,5 child from dual
union all select 5 parent,8 child from dual
union all select 6 parent,5 child from dual
union all select 7 parent,3 child from dual
union all select 7 parent,5 child from dual
union all select 8 parent,6 child from dual
我的目標(biāo)是獲得節(jié)點(diǎn)X的所有后代(孩子,孩子的孩子等)的節(jié)點(diǎn).假設(shè)2.我的預(yù)期結(jié)果是:3,4,5,6,8.
我知道我可以設(shè)計(jì)一個(gè)這樣的查詢:
SELECT child,sys_connect_by_path(child,'/')
FROM T
START WITH parent = 2
CONNECT BY NOCYCLE PRIOR child = PARENT;
這樣一個(gè)查詢的問題是,它會(huì)遍歷所有可能的路徑,直到它們循環(huán),并且在我的實(shí)際數(shù)據(jù)中有太多的路徑.結(jié)果包括許多重復(fù) – 這里是:
child | sys_connect_by_path (for information)
3 | /3
4 | /3/4
5 | /3/4/5
8 | /3/4/5/8
6 | /3/4/5/8/6
6 | /3/6
5 | /3/6/5
8 | /3/6/5/8
4 | /4
5 | /4/5
8 | /4/5/8
6 | /4/5/8/6
8 | /8
6 | /8/6
5 | /8/6/5
我的實(shí)際數(shù)據(jù)要復(fù)雜得多.這樣的查詢的執(zhí)行成本是如此巨大,使得我的TEMP表空間(可自動(dòng)擴(kuò)展)達(dá)到10Gb(最初為500Mb),并且由于磁盤已滿,我的數(shù)據(jù)庫實(shí)際上被破壞.
我試圖設(shè)計(jì)這樣的查詢(遞歸WITH子句):
WITH descendants(node) AS
( SELECT 2 node FROM dual
UNION ALL
(
SELECT child
FROM T
INNER JOIN descendants D
ON T.parent = D.node
MINUS SELECT node FROM descendants
)
)
SELECT * FROM descendants
我遇到的問題是:
>使用Oracle 10g,這沒有實(shí)現(xiàn)(ORA-32033:不支持的列別名,一些客戶使用Oracle 9或10)
>使用Oracle 11g,我得到ORA-32041:遞歸WITH子句中的UNION ALL操作必須只有兩個(gè)分支.如果我刪除了MINUS子句,我將獲得循環(huán)(ORA-32044:在執(zhí)行遞歸WITH查詢時(shí)檢測(cè)到循環(huán)).
您如何查詢我的原始數(shù)據(jù)以有效地獲得這些節(jié)點(diǎn)3,8? PL / sql解決方案也受到歡迎.
謝謝.
總結(jié)
以上是生活随笔為你收集整理的oracle表分层,sql – 对非分层数据的Oracle分层查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MongoDB同步到Oracle,Mon
- 下一篇: oracle备份片校验,oracle r