让我们假设接下来的两个表:
users (username, region, location, department, subdepartment)
和
structure (region, location, department, subdepartment)
开始时,在users表中,每个用户名都显示在一条记录中。我希望如果用户名将子部门列为空,则自动分发到结构表中为该部门定义的所有子部门。
意思是,在用户表中只有一条记录,最后会有N条记录,其中N代表结构表中为原始区域,位置,部门组合定义的子部门数。
我已尝试用MERGE语句执行此操作,但我无法弄明白。我怎么能这样做? 谢谢!
答案 0 :(得分:2)
速度可以这样做:
insert into users
select
u.username, u.region, u.location, u.department, s.subdepartment
from users u join structure s
on (u.region=s.region and u.location=s.location and u.department = s.department)
where u.subdepartment is null;
delete from users where subdepartment is null;
但是,对于上述内容,您必须确保每个部门都有子部门。(如果不是这样,则必须执行一些简单的PL / SQL)
答案 1 :(得分:0)
create table table01 (
code int,
name varchar(50),
old int
);
create table table02 (
code int,
name varchar(50),
old int
);
insert into table01 values (1, 'A', 10);
insert into table01 values (9, 'B', 12);
insert into table01 values (3, 'C', 14);
insert into table01 values (4, 'D', 16);
insert into table01 values (5, 'E', 18);
insert into table02 values (1, 'AA', null);
insert into table02 values (2, 'BB', 123);
insert into table02 values (3, 'CC', null);
insert into table02 values (4, 'DD', null);
insert into table02 values (5, 'EE', null);
select * from table01 a order by 2;
select * from table02 a order by 2;
merge into table02 a using (
select b.code, b.old from table01 b
) c on (
a.code = c.code
)
when matched then update set a.old = c.old
;