日期:2014-05-16  浏览次数:20345 次

在数据库中对树进行遍历查询(转)
最近看到同事用到了这个功能,恰好也发现了一篇好文章,就转过来了。

在数据库中对树进行遍历查询,看看如何实现,这里的例子是用oracle来实现。

ORACLE Recursion query for TREE with "connect by/start with"    
-- Tirle        : Recursion query for TREE with "connect by/start with"
-- Author       : Rake Gao
-- Create Date  : 2005-08-22
-- Version      : 2.0
-- Last Modify  : 2005-08-22

  目  录
一、测试准备
二、实现各种查询要求
三、要点总结


  正  文
一、测试准备
1、先假设有如下部门结构。
       1
     /  \
    2    3
   /\    /|\
  4  5  6 7 8

2、然后建立测试表和数据。
drop table t_dept_temp;
create table t_dept_temp(
  DEPT_ID    NUMBER(2)    NOT NULL,
  PARENT_ID  NUMBER(2)    ,
  DEPT_NAME  VARCHAR2(10) ,
  AMOUNT     NUMBER(3)           --人数
);
delete t_dept_temp;
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (1,null,'1'    ,2);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (2,1   ,'1-2'  ,15);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (3,1   ,'1-3'  ,8);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (4,2   ,'1-2-4',10);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (5,2   ,'1-2-5',9);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (6,3   ,'1-3-6',17);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (7,3   ,'1-3-7',5);
insert into t_dept_temp (DEPT_ID,PARENT_ID,DEPT_NAME,AMOUNT) values (8,3   ,'1-3-8',6);
commit;

SQL> select * from t_dept_temp;

DEPT_ID PARENT_ID DEPT_NAME  AMOUNT
------- --------- ---------- ------
      1           1               2
      2         1 1-2            15
      3         1 1-3             8
      4         2 1-2-4          10
      5         2 1-2-5           9
      6         3 1-3-6          17
      7         3 1-3-7           5
      8         3 1-3-8           6

3、调整一下输出格式
col DEPT_ID format A10;

二、接下来实现各种查询要求
1、部门2及其所有下级部门。
SELECT LPAD(' ',2*(LEVEL - 1), ' ')||DEPT_ID AS DEPT_ID,
       PARENT_ID,DEPT_NAME,AMOUNT
  FROM t_dept_temp
  CONNECT BY PARENT_ID = PRIOR DEPT_ID  -- 找出所有PARENT_ID等于当前记录DEPT_ID的记录。
  START WITH DEPT_ID = 2             &n