我有一些带有外键的表。表的结构并不重要。例如,表A是顶层表。表B和C在表A上具有外键,而表D,E和F和G在表B和C上具有外键。 问题是:有没有办法从表A中克隆行之一 使用SQL进行所有操作(行B-G)?
答案 0 :(得分:0)
您没有提供结构或数据,因此您必须使用我的示例。基本思路是,随着从父级到子级的进行,只需要在相应的PK列中选择适当的FK列。
-- create base tables
create table a (a_id integer, a_col1 text, constraint a_pk primary key (a_id));
create table b (b_id integer, a_id integer, b_col1 text
, constraint b_pk primary key (b_id)
, constraint b_fk_a foreign key (a_id)
references a(a_id)
);
create table g (g_id integer, b_id integer, g_col1 text
, constraint g_pk primary key (g_id)
, constraint g_fk_b foreign key (b_id)
references b(b_id)
);
-------------------------------------------------------------------------------------------------------
-- populate
insert into a (a_id,a_col1) values (11,'ta1'), (12,'ta2');
insert into b (b_id,a_id,b_col1) values (21,11,'tb1'), (22,11,'tb2'), (23,12,'tb3'), (24,12,'tb4');
insert into g (g_id,b_id,g_col1) values (71,21,'tg1'), (72,21,'tg2'), (73,22,'tg3'), (74,22,'tg4')
, (75,23,'tg5'), (76,23,'tg6'), (77,24,'tg7'), (78,24,'tg8');
-------------------------------------------------------------------------------------------------------
-- Soution: clone a_id 12
create table a_clone as
select *
from a
where a_id = 12;
create table b_clone as
select *
from b
where a_id = 12;
create table g_clone as
select *
from g
where b_id in
(select b_id
from b
where a_id = 12
);
-- done
Sticky Bit的“想到”建议是可行的,但并非一帆风顺。我相信上面的内容很简单。