為 了更好的查詢一個樹狀結構的表,在Oracle的PL/SQL中提供樂一個誘人的特性——CONNECT BY子句。它大大的方便了我們查找樹狀表:遍歷一棵樹、尋找某個分支......,但還是存在一些不足。在Oracle 10G,就對這個特性做了增強。下面就舉例說明一下。
樹狀一般都是在一條記錄中記錄一個當前節點的ID和這個節點的父ID來實現。但是,一旦數據中出現了循環記錄,如兩個節點互為對方父節點,系統就會報ORA-01436錯誤,例如:
insert into t_tonedirlib(dirindex, fatherindex, dirname, status) values (666, 667, '123', 5);
insert into t_tonedirlib(dirindex, fatherindex, dirname, status) values (667, 666, '456', 5);
select dirindex, fatherindex, RPAD(' ', 2*(LEVEL-1)) || dirname from t_tonedirlib
start with fatherindex = 666
connect by fatherindex = PRior dirindex;
select CONNECT_BY_ISCYCLE, dirindex, fatherindex, RPAD(' ', 2*(LEVEL-1)) || dirname
from t_tonedirlib
start with fatherindex = 666
connect by NOCYCLE fatherindex = prior dirindex
CONNECT_BY_ISCYCLE DIRINDEX FATHERINDEX RPAD(' ',2*(LEVEL-1))||dirname
;
----------------- ---------------- ---------------------------------
0 667 666 456
1 666 667 123
2 rows selected查找樹狀表中的葉子節點不是件容易事。可以給表增加了一個字段來描述這個節點是否為葉子節點來解決問題,但這樣做有很大的弊端:需要通代碼邏輯來保證這個字段的正確性。
Oracle 10G中提供了一個新特性 CONNECT_BY_ISLEAF 來解決這個問題。簡單點說,這個屬性結果表明當前節點在滿足條件的查詢結果中是否為葉子節點, 0不是,1是。
select CONNECT_BY_ISLEAF, dirindex, fatherindex, RPAD(' ', 2*(LEVEL-1)) || dirname
from t_tonedirlib
start with fatherindex = 0
connect by fatherindex = prior dirindex
CONNECT_BY_ISLEAF DIRINDEX FATHERINDEX RPAD(' ',2*(LEVEL-1))||dirname
----------------- ---------------- ---------------------------------
0 1 0 中文經典
0 52 1 kkkkkkk
1 70 52 222
1 58 52 sixx
1 59 52 seven
1 69 52 uiouoooo
1 55 52 four
1 7 1 流行風云
0 8 1 影視金曲
1 1111 8 aaa
1 1112 8 bbb
1 1113 8 ccc
1 9 1 古典音樂
0 81 1 小熊之家
1 104 81 龍珠
1 105 81 snoppy
1 101 81 叮當1
1 102 81 龍貓
1 103 81 叮當2
0 2 0 熱門流行
1 31 2 有獎活動
1 32 2 相約香格里拉
1 50 2 新浪彩鈴
0 3 0 老歌回放
1 333 3 老電影
1 335 3 懷舊金曲
新聞熱點
疑難解答