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;
copy code

 

 1. Look forward (from the query itself all the way to the top institution)

比如:
select distinct departno,departname,levelfrom deptconnect by prior topno=departnostart withdepartno='005';  




  2. Look back: (from the query itself all the way to the bottom institution)

 

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



In the above statement, PRIOR is used to represent the previous record. For example, CONNECT BY PRIOR ID=PRAENTID means that the ID of the previous record (such as the root record ) is the ( next ) PRAENTID of this record, that is, the father of this record is the previous record.

 

Example of multi-table query:

 

    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=327074766&siteId=291194637