Oracle通過遞迴查詢父子兄弟節點方法示例

2022-09-21 10:12:09 字數 2201 閱讀 2729

前言

說到oracle中的遞迴查詢語法,我覺得有一些資料庫基礎的童鞋應該都知道,做專案的時候應該也會用到,下面本文就來介紹下關於oracle通過遞迴查詢父子兄弟節點的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。

方法如下:

1、查詢某節點下所有後代節點(包括各級父節點)

// 查詢id為www.cppcns.com101的所有後代節點,包含101在內的各級父節點

select t.* from sys_org t start with id = '101' connect by parent_id = prior id

2、查詢某節點下所有後代節點(不包含各級父節點)

select t.*

from sys_org t

where not exists (select 1 from sys_org s where s.parent_id = t.id)

start with id = '101'

connect by parent_id = prior id

3、查詢某節點所有父節點(所有祖宗節點)

select t.*

from sys_org t

start with id = '401000501'

connect by prior parent_id = id

4、查詢某節點所有的兄弟節點(親兄弟)

select * from sys_org t

where exists (select * from sys_org s where t.parent_id=s.parent_id and s.id='401000501')

5、查詢某節點所有同級節點(族節點),假設不設定級別字段

with tmp as(

select t.*, level leaf

fr sys_org t

start with t.parent_id = '0'

connect by t.parent_id = prior www.cppcns.comt.id)

select *

from tmp

where leaf = (select leaf from tmp where id = '401000501');

這裡使用兩個技巧,乙個是使用了level來標識每個節點在表中的級別,還有就是使用with語法模擬出了一張帶有級別的臨時表

6、查詢某節點的父節點及兄弟節點(叔伯節點)

with tmp as(

select t.*, level lev

from sys_org t

start with t.parent_id = '0'

connect by t.parent_id = prior t.id)

select b.*

from tmp b,(select *

from tmp

where id = '401000501' and lev = '2') a

where b.lev = '1'

union all

select *

from tmp

where parent_iwww.cppcns.comd = (select distinct x.id

from tmp x, --祖父

tmp y, --父親

(select *

from tmp

where id = '401000501' and lev > '2') z --兒子

where y.id = z.parent_id and x.id = y.pare程式設計客棧nt_id);

這裡查詢分成以下幾步。

首先,將全表都使用臨時表加上級別;

其次,根據級別來判斷有幾種型別,以上文中舉的例子來說,有三種情況:

(1)當前節點為頂級節點,即查詢出來的lev值為1,那麼它沒有上級節點,不予考慮。

(2)當前節點為2級節點,查詢出來的lev值為2,那麼就只要保證lev級別為1的就是其上級節點的兄弟節點。

(3)其它情況就是3以及以上級別,那麼就要選查詢出來其上級的上級節點(祖父),再來判斷祖父的下級節點都是屬於該節點的上級節點的兄弟節點。

最後,就是使用union將查詢出來的結果進行結合起來,形成結果集。

總結本文標題: oracle通過遞迴查詢父子兄弟節點方法示例

本文位址:

oracle遞迴查詢父子關係記錄

資料庫中常要處理父子關係的記錄,在oracle中可以用查詢語句一次把所有的子記錄全部取出來。例如下 t1t11 t111 t1111 t12t121 t1211 db資料字段如下 task id task name t.parent task id 000001 t1 000002 t11 0000...

oracle 遞迴查詢 Oracle遞迴查詢

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 distr...

MySQL遞迴查詢父子節點

create table folder id bigint 20 not null,parent id bigint 20 default null,primary key id 建立函式 create function getparlist rootid bigint returns varcha...