Oracle遞迴查詢

2021-05-10 04:15:06 字數 1408 閱讀 2849

oracle遞迴查詢

1、資料庫中有乙個表,結構如下所示:

表名:tbinvoice

字段:idnameparent_id

每一行記錄表示乙個發票,parent_id

表示它的父物件id

,假設現在表中有如下資料:

id name parent_id

1

aa 2              bb 1

3cc 1 4

dd 2

5ee 2 6

ff 3

7gg 4

8hh 5

9jj 5

10             kk 6

這樣就形成了如下乙個樹,我們暫且稱它們為乙個家族吧。

現在有這樣乙個需求,給定乙個id

,要查出這個id

所述家族中的所有id

select id from tbinvoice connect by prior id=parentid start with id=5

在整個過程,起關鍵作用的就是prior 這個關鍵字:

1.  當

prior

在parentid

之前時,說明

parentid

優先,如果

start with id=5

,那麼從

id=5

的那條記錄開始查詢,後面的記錄都 必須 是

id =前面記錄的

parentid

,這樣就表明是向上進行查詢,追溯它所有的祖先。

2.當

prior

在id之前時,說明

id 優先,如果

start with id=5

,那麼從

id=5

的那條記錄開始查詢,後面的記錄都必須是

parentid=

前面記錄的

id ,這就相當於是向下進行,尋找它所有的子孫。

3.如果不需要指定從那個id開始,則

start with id=5這句

不寫即

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

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