遇到的需求是查看我們給使用者建立的網站的欄目被調整了N多次後現在是什麼樣子了,於是在網上找到相關的資料,用oracle特有的語句查詢。
詳細內容轉自http://www.javaeye.com/topic/287749
Start with...Connect By子句遞迴查詢一般用於一個表維護樹形結構的應用。建立樣本表:CREATE TABLE TBL_TEST
(
ID NUMBER,
NAME VARCHAR2(100 BYTE),
PID NUMBER DEFAULT 0
); 插入測試資料:INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('1','10','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('2','11','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('3','20','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('4','12','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('5','121','2'); 從Root往樹末梢遞迴select * from TBL_TEST
start with id=1
connect by prior id = pid 從末梢往樹ROOT遞迴select * from TBL_TEST
start with id=5
connect by prior pid = id=====對於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
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
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
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 後面所放的欄位是有關係的,它指明了查詢的方向。
其他參考:
http://zhaolinjnu.blog.163.com/blog/static/2280005200841621159121/
http://www.javaeye.com/topic/287749
http://www.javaeye.com/wiki/topic/746687