ITPub博客

首页 > 数据库 > Oracle > 裁剪树

裁剪树

原创 Oracle 作者:壹頁書 时间:2013-12-24 22:51:42 0 删除 编辑
最近需要做实验,用到hr的employees表,但是这个表的数据很多,不容易看清结果。
所以需要精简他的数据,但是还要维护他原有的树形结构。

准备实验数据

  1. create table emp as select * from hr.employees;

  2. select lpad(employee_id,level*4,' ') from emp
  3. start with manager_id is null
  4. connect by prior employee_id=manager_id;
 100
     101
         108
             109
             110
             111
             112
             113
         200
         203
         204
         205
             206
     102
         103
             104
             105
             106
             107
     114
         115
         116
         117
         118
         119
     120
         125
         126
         127
         128
         180
         181
         182
         183
     121
    ......
 
上面的结果红色部分保留(101,102,114及其子节点保留),其余删除。

第一种方法,不等连接

  1. delete from emp where employee_id not in(
  2.     select t1.employee_id from (
  3.         --自顶向下访问
  4.         select employee_id,sys_connect_by_path(employee_id,\',\') path
  5.         from emp
  6.         start with manager_id is null
  7.         connect by prior employee_id=manager_id
  8.     ) t1
  9.     inner join (
  10.         select employee_id target from emp where employee_id in(101,102,114)    
  11.     ) t2
  12.     on instr(t1.path,','||t2.target)!=0
  13. ) and employee_id!=100;

第二种方法,根据节点遍历树

  1. delete from emp where employee_id not in
  2. (
  3.     select t1.employee_id from
  4.     (
  5.         --根据101,102,114 分别自顶向下和自底向上遍历
  6.         select employee_id from emp
  7.         start with manager_id in (101,102,114)
  8.         connect by prior employee_id=manager_id
  9.         union
  10.         select employee_id from emp
  11.         start with manager_id in (101,102,114)
  12.         connect by employee_id =prior manager_id
  13.     ) t1,
  14.     (
  15.         select employee_id,sys_connect_by_path(employee_id,\',\') path
  16.         from emp
  17.         start with manager_id is null
  18.         connect by prior employee_id=manager_id
  19.     ) t2
  20.     where t1.employee_id=t2.employee_id
  21. );

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1064183/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Oracle OMF 为鸡肋
下一篇: 反向Ajax之WebSocket
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339838