1. 程式人生 > >Oracle 迴圈遞迴遍歷樹結構查詢

Oracle 迴圈遞迴遍歷樹結構查詢

在專案中經常會接觸樹結構的頁面; 經常會寫關於查詢某個樹節點的所有子節點的方法,若使用java的for迴圈或者遞迴不但效率低又好效能。所以推薦使用oracle 提供的connect by prior start with  的遞迴查詢用法。

oracle的connect by prior start with  是個雙向查詢樹結構的功能,既可以查詢子節點 ,又可以根據子節點查詢上流的所有父節點; 舉例如下:

準備的SQL:

drop table t_tmp_20151027;
create table t_tmp_20151027(
       code varchar2(10) primary key,
       name varchar2(50),
       parent_code varchar2(10),
       create_time date default sysdate,
       active char(1) default 'Y'
);
comment on column t_tmp_20151027.code is '部門編碼';
comment on column t_tmp_20151027.name is '部門名稱';
comment on column t_tmp_20151027.parent_code is '父級編碼';
comment on column t_tmp_20151027.create_time is '建立日期 預設sysdate';
comment on column t_tmp_20151027.active is '是否有效(Y有效,預設)';

select * from t_tmp_20151027;

insert into t_tmp_20151027(code, name, parent_code) values('D00001', '總裁辦公室', null);
insert into t_tmp_20151027(code, name, parent_code) values('D01000', '企業發展辦公室', 'D00001');
insert into t_tmp_20151027(code, name, parent_code) values('D10000', '職能運營本部', 'D01000');
insert into t_tmp_20151027(code, name, parent_code) values('D10001', '華東執行本部', 'D10000');
insert into t_tmp_20151027(code, name, parent_code) values('D10002', '華南執行本部', 'D10000');

insert into t_tmp_20151027(code, name, parent_code) values('D20000', '資訊科技部', 'D01000');
insert into t_tmp_20151027(code, name, parent_code) values('D20001', 'IT開發部', 'D20000');
insert into t_tmp_20151027(code, name, parent_code) values('D20002', '運維管理部', 'D20000');
具體用法:
--通過父節點查詢此節點及向下遞迴遍歷所有的子節點...
select a.*
  from t_tmp_20151027 a, 
       (select distinct code
          from t_tmp_20151027
         where active = 'Y'
        connect by prior code  = parent_code
               and active = 'Y'
         start with code = 'D00001') b
 where 1 = 1
   and a.code = b.code
   and a.active = 'Y';
   
  
--通過子節點查詢此節點及向上遞迴遍歷所有的父節點  
select a.*
  from t_tmp_20151027 a, 
       (select distinct code
          from t_tmp_20151027
         where active = 'Y'
        connect by prior parent_code  = code
               and active = 'Y'
         start with code = 'D20000') b
 where 1 = 1
   and a.code = b.code
   and a.active = 'Y';