合并具有相同主键的两个表

时间:2014-04-20 12:24:55

标签: sql oracle merge

示例i在Employee中包含以下字段的值。

CREATE TABLE Department (
D#      NUMBER(5)   NOT NULL, /* Department number      */
DName       VARCHAR2(30)    NOT NULL, /* Department name        */
Manager#    CHAR(5)     NOT NULL, /* Department manager number  */
MSDate      DATE,             /* Manager start date         */
    total_staff_number NUMBER(3),
CONSTRAINT Department_PK PRIMARY KEY(D#),
CONSTRAINT Department_CK UNIQUE(DName)
);

CREATE TABLE Employee (
E#      CHAR(5)     NOT NULL, /* Employee number        */
Name        VARCHAR2(30)    NOT NULL, /* Employee name      */
    D#      NUMBER(5),        /* Department number      */
CONSTRAINT Employee_PK PRIMARY KEY(E#),
CONSTRAINT Employee_FK2 FOREIGN KEY (D#) REFERENCES Department (D#)
);

在我的数据库中。 DEPARTMENT =' SPORTS' = D#= 5,DEPARTMENT =' GAMES' = D#= 3; 合并DEPARTMENT =' SPORTS' INTO DEPARTMENT =' GAMES' ,经理仍将保持不变,员工.D#= 5将更改为employee.D#= 3

MERGE INTO EMPLOYEE TARGET
USING EMPLOYEE SOURCE WHERE D#=5 ON (
TARGET.D# = SOURCE.D#;
}
WHEN MATCHED THEN
UPDATE SET SOURCE.D#=3;
UPDATE DEPARTMENT.D# SET total_staff_number = total_staff_number - 1 where DEPARTMENT.D# = SOURCE.D#;
UPDATE DEPARTMENT.D# SET total_staff_number = total_staff_number - 1 where DEPARTMENT.D# = TARGET.D#;

但我的逻辑似乎错了。 任何解决方案?

1 个答案:

答案 0 :(得分:0)

将员工从体育运动转移到游戏将简单地更新离职列以指向新部门。问题是你之后将如何处理悬空部门的运动?

对于在体育界工作的所有员工,请更改为游戏。

update employee
   set d# = 3
 where d# = 5;

计算部门游戏中的nr员工,并更新员工柜台。

update department
   set total_staff_number = (
          select count(*)
            from employee
           where d# = 3
       )
 where d# = 3;