遞歸查詢: 使用語句SQL語句即可把整個遞歸樹全部查詢出來。
1.語法:
SELECT [LEVEL], column, expr...
FROM table
[WHERE condition(s)]
[START WITH condition(s)]
[CONNECT BY PRIOR condition(s)] ;
--語法
1 select … from tablename
2 start with 條件1
3 connect by 條件2
4 where 條件3;
? ?? 簡單說來是將一個樹狀結(jié)構(gòu)存儲在一張表里,比如一個表中存在兩個字段:org_id,parent_id,那么通過表示每一條記錄的parent是誰,就可以形成一個樹狀結(jié)構(gòu),用上述語法的查詢可以取得這棵樹的所有記錄,其中:?
? ? ? ? 條件1 是根結(jié)點的限定語句,當然可以放寬限定條件,以取得多個根結(jié)點,實際就是多棵樹。
? ? ? ? 條件2 是連接條件,其中用PRIOR表示上一條記錄,比如 CONNECT BY PRIOR org_id = parent_id;就是說上一條記錄的org_id 是本條記錄的parent_id,即本記錄的父親是上一條記錄。
? ? ? ?? 條件3 是過濾條件,用于對返回的所有記錄進行過濾。
? ? 簡單介紹如下:
? ? ? ? 在掃描樹結(jié)構(gòu)表時,需要依此訪問樹結(jié)構(gòu)的每個節(jié)點,一個節(jié)點只能訪問一次,其訪問的步驟如下:
? ? ? ? 第一步:從根節(jié)點開始;
? ? ? ? 第二步:訪問該節(jié)點;
? ? ? ? 第三步:判斷該節(jié)點有無未被訪問的子節(jié)點,若有,則轉(zhuǎn)向它最左側(cè)的未被訪問的子節(jié),并執(zhí)行第二步,否則執(zhí)行第四步;
? ? ? ? 第四步:若該節(jié)點為根節(jié)點,則訪問完畢,否則執(zhí)行第五步;
? ? ? ? 第五步:返回到該節(jié)點的父節(jié)點,并執(zhí)行第三步驟。
? ? ? ? 總之:掃描整個樹結(jié)構(gòu)的過程也即是中序遍歷樹的過程。
2.例子:
--遞歸查詢(樹結(jié)構(gòu))
select prior t.item_id,
? ? ? prior t.caption_explain,
? ? ? t.item_id,
? ? ? t.caption_explain
? from bwptest1.sys_tree_list t
start with t.item_id = 'flow_menu'
connect by prior t.item_id = t.parent_id;
--1.主鍵ID,parent_id
--2.prior 的位置
? ? ? ? ? --connect by prior 主鍵ID 從上往下
? ? ? ? ? --connect by prior parent_id 從下往上
--樹結(jié)構(gòu),從上往下遍歷
select prior t.item_id,
? ? ? prior t.caption_explain,
? ? ? t.item_id,
? ? ? t.caption_explain
? from bwptest1.sys_tree_list t
start with t.item_id = 'flow_menu'
connect by prior t.item_id = t.parent_id;
--樹結(jié)構(gòu),從下往上遍歷
select prior t.item_id,
? ? ? prior t.caption_explain,
? ? ? t.item_id,
? ? ? t.caption_explain
? from bwptest1.sys_tree_list t
start with t.item_id = 'flow_process_manage'
connect by prior t.parent_id = t.item_id;
select prior t.item_id,
? ? ? prior t.caption_explain,
? ? ? t.item_id,
? ? ? t.caption_explain
? from bwptest1.sys_tree_list t
start with t.item_id = 'flow_process_manage'
connect by t.item_id = prior t.parent_id;
--使用level 和 lpad函數(shù),在output中顯示樹形層次(注意中文字符 lengthb,英文字符 length)
SELECT prior t.item_id,
? ? ? prior t.caption_explain,
? ? ? t.item_id,
? ? ? t.caption_explain,
? ? ? level,
? ? ? lengthb(prior t.caption_explain),
? ? ? lengthb(prior t.caption_explain) + (level * 2)-2,
? ? ? lpad(t.caption_explain,
? ? ? ? ? ? lengthb(t.caption_explain) + (level * 2)-2,
? ? ? ? ? ? '_') chart
? FROM bwptest1.sys_tree_list t
start with t.item_id = 'flow_menu'
connect by prior t.item_id = t.parent_id;