Oracle's recursive query (tree query)

  At work, we often encounter the need to display the data in the database in the form of a tree. Let's take a look at how this requirement is implemented in Oracle.

First of all, we need to have a tree-shaped table structure (of course, sometimes the table structure is not a typical tree-shaped structure, but multi-table storage, and a tree needs to be generated according to the multi-table connection query)

1. Tree table structure:
node ID parent ID node name


2. Usage: 
select  node ID, node name, level from  table name connect  by  prior node ID = superior node ID start  with  superior node ID = node value


 

Description:
1. The common tree structure is company organization, region...
2. To find the structure above the node ID, or the structure below, change the left and right order of "node ID = superior node ID".
3. Level is a special field of Oracle, which means "level". The next level node of the current node ID is "1".

 

Test SQL: 1. Create a table structure

create table Dept(DepartNO  varchar2(10),DepartName  varchar2(20),TopNo    varchar2(10));  




 Insert data: 

insert into Dept values('001','Board of Directors','0');
commit;
insert into Dept values('002','President's Office','001');
commit;
insert into Dept values('003', 'Finance Department','001');
commit;
insert into Dept values('004','Marketing Department','002');
commit;
insert into Dept values('005','PR Department','002' );
commit;
insert into Dept values('006','Sales Department','002');
commit;
insert into Dept values('007','Distribution','006');
commit;
insert into Dept values ('008','Business Development Office','004');
commit;
insert into Dept values('009' ,'Sales Section','007');
commit;
复制代码

 

 1,向前查 (从查询本身一直到最上面的机构)

比如:
select   distinct  departno,departname, level
from  dept
connect 
by  prior topno = departno
start 
with
departno
= ' 005 ' ;

  2,向后查:(从查询本身一直到最下面的机构)

 

select   distinct  departno,departname, level
from  dept
connect 
by  prior departno = topno
start 
with
topno
= ' 001 ' ;

上面语句中用PRIOR表示上一条记录,比如 CONNECT BY PRIOR ID=PRAENTID就是说上一条记录的ID(比如根记录)是(下一条)本条记录的PRAENTID,即本记录的父亲是上一条记录。

 

多表查询例子:

 

    select a.ar_file_name,a.ar_depart_id,b.depart_no,b.depart_name

 from t_archives a left join csr_department b on(a.ar_depart_id = b.depart_no)
 where a.ar_depart_id in(
 	select a.depart_no
           from csr_department a 
          start with a.depart_no in ('8637')
         connect by prior a.depart_id = a.parent_id
 )

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327074813&siteId=291194637