oracle复制表中的树

7nbnzgx9  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(401)

我正在寻找一些有趣的简单算法,将树的一部分复制(克隆)到树的另一部分。
我们有一张table:

create table tree (
     id integer not null,
     parent_id integer,
     value varchar2(255),
     CONSTRAINT tab_pk PRIMARY KEY (id)
  );

begin
  insert into tree(id, parent_id, value) values (1, null, 'A');
  insert into tree(id, parent_id, value) values (2, 1, 'B');
  insert into tree(id, parent_id, value) values (3, 1, 'C');
  insert into tree(id, parent_id, value) values (4, 2, 'BC');
  insert into tree(id, parent_id, value) values (8, 4, 'BCX');
  insert into tree(id, parent_id, value) values (5, 2, 'BD');
  insert into tree(id, parent_id, value) values (6, 3, 'CA');
  insert into tree(id, parent_id, value) values (7, 3, 'CD');
end;
/


https://dbfiddle.uk/?rdbms=oracle_18&fiddle=9fe802f144a3af0663754cfb3e8dc1ba
如何轻松地复制树“b”(id=2),所有子树都在“ca”(id=6)下?
甲骨文18-19c。

fruv7luv

fruv7luv1#

我试着理解你的问题
原始查询提供此输出

select level, id, 
       lpad ( ' ', level, ' ' ) || value name 
from   tree
start  with parent_id is null
connect by prior id = parent_id;

LE  ID  NAME
1   1    A
2   2     B
3   4      BC
4   8       BCX
3   5      BD
2   3     C
3   6      CA
3   7      CD

然后你说你想要树“b”(id=2),所有子树都在“ca”(id=6)下

select level, id, 
       lpad ( ' ', level, ' ' ) || value name 
from   tree
start  with id = 2
connect by prior id = parent_id
union all
-- tree to clone
select level, id, 
       lpad ( ' ', level, ' ' ) || value name 
from   tree
start  with id = 6 or id=7 
connect by prior id = parent_id;

LE  ID  NAME
1   2    B
2   4     BC
3   8      BCX
2   5     BD
1   6    CA
1   7    CD

db<>小提琴

相关问题