oracle中用START WITH...CONNECT BY PRIOR子句實現遞歸查詢

今天發如今oracle中的select語句能夠用START WITH...CONNECT BY PRIOR子句實現遞歸查詢,connect by 是結構化查詢中用到的,其基本語法是: 

select ... from tablename start with cond1 
connect by cond2 
where cond3; 

簡單說來是將一個樹狀結構存儲在一張表裏,好比一個表中存在兩個字段: 
id,parentid那麼經過表示每一條記錄的parent是誰,就能夠造成一個樹狀結構。 

用上述語法的查詢能夠取得這棵樹的全部記錄。 

其中COND1是根結點的限定語句,固然能夠放寬限定條件,以取得多個根結點,實際就是多棵樹。 

COND2是鏈接條件,其中用PRIOR表示上一條記錄,好比 CONNECT BY PRIOR ID=PRAENTID就是說上一條記錄的ID是本條記錄的PRAENTID,即本記錄的父親是上一條記錄。 
COND3是過濾條件,用於對返回的全部記錄進行過濾。 

對於oracle進行簡單樹查詢(遞歸查詢) 
DEPTID PAREDEPTID NAME 
NUMBER NUMBER CHAR (40 Byte) 
部門id 父部門id(所屬部門id) 部門名稱 

經過子節點向根節點追朔.  sql

select * from persons.dept start with deptid=76 connect by prior paredeptid=deptid

經過根節點遍歷子節點.  oracle

select * from persons.dept start with paredeptid=0 connect by prior deptid=paredeptid
   可經過level 關鍵字查詢所在層次.

select a.*,level from persons.dept a start with paredeptid=0 connect by prior deptid=paredeptid

再次複習一下:start with ...connect by 的用法, start with 後面所跟的就是就是遞歸的種子。 

遞歸的種子也就是遞歸開始的地方 connect by 後面的"prior" 若是缺省:則只能查詢到符合條件的起始行,並不進行遞歸查詢; 

connect by prior 後面所放的字段是有關係的,它指明瞭查詢的方向。 
spa

select FIRST_VALUE(deptid) OVER (ORDER BY LEVEL DESC ROWS UNBOUNDED PRECEDING) AS firstdeptid from persons.dept start with deptid=76 connect by prior paredeptid=deptid
相關文章
相關標籤/搜索