connect by 級聯查詢
1、建表、插入測試資料
create table t_menu(id int,name varchar2(50),parentId int);
2、測試查詢
(1)查詢 以id=1為起始值 及其下所有子孫;
select * from t_menu connect by parent_id=prior id start with id=1;
(2)查詢以id=1其下所有子孫,但不含有其本身,可以看到比上面查詢語句少一條記錄。
select * from t_menu t connect by t.parentid = prior id start with t.id = 1
(3)查詢id=9的父親祖輩
select * from t_menu t connect by t.id = prior t.parentid start with t.id = '9'
(4)查詢時新增層級level,方便前端展示樹選單時做判斷使用。
select level,t.* from t_menu t connect by t.parentid = prior id start with t.id = 1
(5)查詢 新增葉子節點列connect_by_isleaf
select connect_by_isleaf,level,t.* from t_menu t connect by t.parentid = prior id start with t.id = 1
上圖可以看出 level=3的都是最後一級,就是葉子節點,0表示非葉子節點,1表示是葉子節點。
(6)展示層級關係 sys_connect_by_path
select sys_connect_by_path(name, '>') as connect_path,t.*
from t_menu t connect by prior id = t.parentid start with t.id = 1