1.1、建立表與插入資料
create table district( id number(10) not null, parent_id number(10), name varchar2(255 byte) not null);alter table district add ( constraint district_pk primary key (id));alter table district add ( constraint district_r01 foreign key (parent_id) references district (id)); insert into district (id, parent_id, name)values (1, null, '四川省');insert into district (id, parent_id, name)values (2, 1, '巴中市');insert into district (id, parent_id, name)values (3, 1, '達州市');insert into district (id, parent_id, name)values (4, 2, '巴州區');insert into district (id, parent_id, name)values (5, 2, '通江縣');insert into district (id, parent_id, name)values (6, 2, '平昌縣');insert into district (id, parent_id, name)values (7, 3, '通川區');insert into district (id, parent_id, name)values (8, 3, '宣漢縣');insert into district (id, parent_id, name)values (9, 8, '塔河鄉');insert into district (id, parent_id, name)values (10, 8, '三河鄉');insert into district (id, parent_id, name)values (11, 8, '胡家鎮');insert into district (id, parent_id, name)values (12, 8, '南壩鎮');insert into district (id, parent_id, name)values (13, 6, '大寨鄉');insert into district (id, parent_id, name)values (14, 6, '響灘鎮');insert into district (id, parent_id, name)values (15, 6, '龍崗鎮');insert into district (id, parent_id, name)values (16, 6, '白衣鎮');commit;
2.1、查詢所有子節點
select *from districtstart with name ='巴中市'connect by prior id=parent_id
2.2、查詢所有父節點
select *from districtstart with name ='平昌縣'connect by prior parent_id=id
只需要交換 id 與parent_id的位置即可
2.3、查詢指定節點的,根節點
select d.*,connect_by_root(d.id),connect_by_root(name)from district dwhere name='平昌縣'start with d.parent_id=1 --d.parent_id is null 結果為四川省connect by prior d.id=d.parent_id
2.4、查詢巴中市下行政組織遞迴路徑
select id,parent_id,name,sys_connect_by_path(name,'->') namepath,levelfrom district start with name='巴中市'connect by prior id=parent_id
3.1、with遞迴子類
with t (id ,parent_id,name) --要有列名as(select id ,parent_id,name from district where name='巴中市'union allselect d.id ,d.parent_id,d.name from t,district d --要指定表和列表,where t.id=d.parent_id)select * from t;
3.2、遞迴父類
with t (id ,parent_id,name) --要有表as(select id ,parent_id,name from district where name='通江縣'union allselect d.id ,d.parent_id,d.name from t,district d --要指定表和列表,where t.parent_id=d.id)select * from t;
oracle 逆向遞迴查詢 oracle遞迴查詢
oracle的遞迴查詢 最近在看公司的oa系統,oa系統中基本都會有節點樹,其中對於樹上的資料展示,就是用了資料庫的遞迴查詢,在這裡總結下遞迴查詢。現在存在如下的一棵樹 不會畫樹,將就一下,該樹對應下面建立的表資料。建立如下表 create table dg id number not null,主...
oracle 逆向遞迴查詢 Oracle遞迴查詢
start with.connect by子句遞迴查詢一般用於乙個表維護樹形結構的應用。建立示例表 create table tbl test id number,name varchar2 100 byte pid number default 0 插入測試資料 insert into tbl t...
Oracle遞迴查詢
有的情況下,我們需要用遞迴的方法整理資料,這才程式中很容易做到,但是在資料庫中,用sql語句怎麼實現?下面我以最典型的樹形結構來說明下如何在oracle使用遞迴查詢。為了說明方便,建立一張資料庫表,用於儲存乙個簡單的樹形結構 sql create tabletest tree id number,p...