oracle 逆向遞迴查詢 Oracle遞迴查詢

2021-10-12 14:17:19 字數 2556 閱讀 4475

start with...connect by子句遞迴查詢一般用於乙個表維護樹形結構的應用。

建立示例表:

create table tbl_test

id number,

name varchar2(100 byte),

pid number default 0

插入測試資料:

insert into tbl_test(id,name,pid) values('1','10','0');

insert into tbl_test(id,name,pid) values('2','11','1');

insert into tbl_test(id,name,pid) values('3','20','0');

insert into tbl_test(id,name,pid) values('4','12','1');

insert into tbl_test(id,name,pid) values('5','121','2');

從root往樹末梢遞迴

select * from tbl_test

start with id=1

connect by prior id = pid

從末梢往樹root遞迴

select * from tbl_test

start with id=5

connect by prior pid = id

有一張表 t

字段:parent

child

兩個欄位的關係是父子關係

寫乙個sql語句,查詢出指定父下面的所有的子

比如a b

a ca e

b b1

b b2

c c1

e e1

e e3

d d1

指定parent=a,選出

a ba c

a eb b1

b b2

c c1

e e1

e e3

sql語句:

select parent,child from test start with parent='a'

connect by prior child=parent

connect by 是結構化查詢中用到的,其基本語法是:

select ... from tablename start by cond1

connect by cond2

where cond3;

簡單說來是將乙個樹狀結構儲存在一張表裡,比如乙個表中存在兩個字段:

id,parentid那麼通過表示每一條記錄的parent是誰,就可以形成乙個樹狀結構。

用上述語法的查詢可以取得這棵樹的所有記錄。

其中cond1是根結點的限定語句,當然可以放寬限定條件,以取得多個根結點,實際就是多棵樹。

cond2是連線條件,其中用prior表示上一條記錄,比如 connect by prior id=praentid就是說上一條記錄的id是本條記錄的praentid,即本記錄的父親是上一條記錄。

cond3是過濾條件,用於對返回的所有記錄進行過濾。

prior和start with關鍵字是可選項

priory運算子必須放置在連線關係的兩列中某乙個的前面。對於節點間的父子關係,prior

運算子在一側表示父節點,在另一側表示子節點,從而確定查詢樹結構是的順序是自頂向下還是

自底向上。在連線關係中,除了可以使用列名外,還允許使用列表示式。start with 子句為

可選項,用來標識哪個節點作為查詢樹型結構的根節點。若該子句被省略,則表示所有滿足查詢

條件的行作為根節點。

完整的例子如select pid,id,name from t_wf_eng_wfkind start with pid =0 connect by prior id = pid

以上主要是針對上層對下層的順向遞迴查詢而使用start with ... connect by prior ...這種方式,但有時在需求需要的時候,可能會需要由下層向上層的逆向遞迴查詢,此是語句就有所變化:例如要實現 select * from table where id in ('0','01','0101','0203','0304') ;現在想把0304的上一級03給遞迴出來,0203的上一級02給遞迴出來,而01現在已經是存在的,最高層為0.而這張table不僅僅這些資料,但我現在只需要('0','01','0101','0203','0304','02','03')這些資料,此時語句可以這樣寫select pid,id,name from v_wf_wfkind_tree where id in (select distinct(id) id from v_wf_wfkind_tree connect by prior pid = id start with id in ('0','01','0101','0203','0304') );

其中start with id in裡面的值也可以替換select 子查詢語句.

注意由上層向下層遞迴與下層向上層遞迴的區別在於start with...connect by prior...的先後順序以及 id = pid 和 pid = id 的微小變化![@more@]

oracle 逆向遞迴查詢 oracle遞迴查詢

oracle的遞迴查詢 最近在看公司的oa系統,oa系統中基本都會有節點樹,其中對於樹上的資料展示,就是用了資料庫的遞迴查詢,在這裡總結下遞迴查詢。現在存在如下的一棵樹 不會畫樹,將就一下,該樹對應下面建立的表資料。建立如下表 create table dg id number not null,主...

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遞迴查詢

有的情況下,我們需要用遞迴的方法整理資料,這才程式中很容易做到,但是在資料庫中,用sql語句怎麼實現?下面我以最典型的樹形結構來說明下如何在oracle使用遞迴查詢。為了說明方便,建立一張資料庫表,用於儲存乙個簡單的樹形結構 sql create tabletest tree id number,p...