Oracle 遞迴查詢

2021-06-24 11:33:09 字數 1244 閱讀 6246

原文:

1. 建表

create table users.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');

2. 語法

select * from …. where [結果過濾條件語句]

start with [and起始條件過濾語句]

connect by prior [and中間記錄過濾條件語句]

3. 例子

查詢所有下級,包括當前條件資料

select * from tbl_test start with id = 1 connect by prior id = pid
注意:此sql能查詢id=1的資料的所有下級,包括id=1的資料,寫sql語句時要注意,因為是從id開始查詢下級,所以connect by prior 子句的條件是id=pid

查詢所有下級,不包括當前條件資料

select * from tbl_test start with pid = 1 connect by prior id = pid

查詢所有上級

select * from tbl_test start with id = 5 connect by prior pid = id
因為是從id開始查詢上級,所以connect by prior 子句的條件是pid=d

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