1. 程式人生 > 其它 >資料庫的級聯查詢:Connect by

資料庫的級聯查詢:Connect by

技術標籤:# oracle

建立測試表,增加測試資料

create table test(superid varchar2(20),id varchar2(20));

insert into test values('0','1');
insert into test values('0','2');

insert into test values('1','11');
insert into test values('1','12');

insert into test values('2','21');
insert into test values('2','22');

insert
into test values('11','111'); insert into test values('11','112'); insert into test values('12','121'); insert into test values('12','122'); insert into test values('21','211'); insert into test values('21','212'); insert into test values('22','221'); insert into test values('22','222'); commit
;

在上表中查詢id=11相關聯的所有的父節點以及所有的子節點資料,級聯sql如下:

select id,superid from TEST t start with id='11' connect by prior superId = id
UNION
select id,superid from TEST t start with id='11' connect by prior id = superId

查詢結果如下圖:
在這裡插入圖片描述
在上表中查詢id=11相關聯的所有的父節點資料,級聯sql如下:

select id,superid from TEST t start with id='11'
connect by prior superId = id

查詢結果如下圖:
在這裡插入圖片描述
在上表中查詢id=11相關聯的所有的子節點資料,級聯sql如下:

select id,superid from TEST t start with id='11' connect by prior id = superId

查詢結果如下圖:
在這裡插入圖片描述
在上表中查詢id=1的本身級子級為2層的資料 ,級聯sql如下:

select id,superid from TEST t start with id='1' connect by prior id = superId and level <= 2

查詢結果如下圖:
在這裡插入圖片描述