對於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
select * from persons.dept start with deptid=76 connect by prior paredeptid=deptid
通過根節點遍曆子節點.
Sql代碼
- select * from persons.dept start with paredeptid=0 connect by prior deptid=paredeptid
select * from persons.dept start with paredeptid=0 connect by prior deptid=paredeptid
可通過level 關鍵字查詢所在層次.
Sql代碼
- select a.*,level from persons.dept a start with paredeptid=0 connect by prior deptid=paredeptid
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 後面所放的欄位是有關係的,它指明了查詢的方向。
練習: 通過子節點獲得頂節點
Sql代碼
- 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
轉自:http://www.javaeye.com/topic/191016