代碼測試
--建立表
create table Dept(ID int,ParentID int,Name varchar(20));
--增長測試數據,和上面的SqlServer數據相同
insert into Dept select 1,0,'AA' from dual;
insert into Dept select 2,1,'BB' from dual;
insert into Dept select 3,1,'CC' from dual;
insert into Dept select 4,2,'DD' from dual;
insert into Dept select 5,3,'EE' from dual;
insert into Dept select 6,0,'FF' from dual;
insert into Dept select 7,6,'GG' from dual;
insert into Dept select 8,7,'HH' from dual;
insert into Dept select 9,7,'II' from dual;
insert into Dept select 10,7,'JJ' from dual;
insert into Dept select 11,9,'KK' from dual;
commit;遞歸
--查詢根節點(父節點)
select * from Dept --查詢基礎表
connect by id=prior parentid --connect by就是字段的關聯關鍵字,prior有預先和前的意思,則是放在哪一個字段前,哪一個就是遞歸的上一層
start with name='II'; --start with則是遞歸的起始位置,也能夠用id或者是parentid。能夠修改II的值測試其餘數據。it
--查詢結果
ID PARENTID NAME
7 II
6 GG
0 FFio
--查詢子節點table
select * from Dept
connect by prior id=parentid --一樣的語句,僅僅改變prior位子,就發生了指向性的變化,就是這裏id爲遞歸上一層。
start with name='II';基礎
--查詢結果
ID PARENTID NAME
7 II
9 KKselect
--測試結果和SqlServer一致,語句卻更精練,簡潔易懂。數據
複製代碼查詢