-3

我有两个名为 EMPLOYEE 和 DEPARTMENT 的表,如下所示:

CREATE table "EMPLOYEE" (
    "EMP_ID"     NUMBER,
    "ENAME"      VARCHAR2(4000),
    "SALARY"     VARCHAR2(4000),
    "COMPANY"    VARCHAR2(4000),
    "CONTACTNO." NUMBER,
    "GENDER"     CHAR(100),
    constraint  "EMPLOYEE_PK" primary key ("EMP_ID")
)

CREATE TABLE  "DEPARTMENT" 
(   
    "DEPT_ID" NUMBER, 
    "DEPT_NAME" VARCHAR2(4000), 
    "LOCATION" VARCHAR2(4000), 
    "CONTACTNO." NUMBER, 
     CONSTRAINT "DEPARTMENT_PK" PRIMARY KEY ("DEPT_ID") ENABLE
)

现在我正在尝试将 EMPLOYEE 表的 Emp_ID 作为 EMPLOYEE 表本身的主键,但它应该作为 DEPARTMENT 表中 DEPT_ID 的外键,请告知如何实现这一点!

4

3 回答 3

2

如果EMPLOYEE要成为父表并且DEPARTMENT要成为子表,则需要在表DEPARTMENT中引用的位置定义外键。外键在子表上创建并引用父表。EMP_IDEMPLOYEE

CREATE TABLE  "DEPARTMENT" 
(   
    "DEPT_ID" NUMBER, 
    "DEPT_NAME" VARCHAR2(4000), 
    "LOCATION" VARCHAR2(4000), 
    "CONTACTNO." NUMBER, 
     CONSTRAINT "DEPARTMENT_PK" PRIMARY KEY ("DEPT_ID") ENABLE,
     CONSTRAINT department_fk FOREIGN KEY( DEPT_ID )
       REFERENCES employee( EMP_ID )
)

当然,根据您的示例,定义外键约束将是一种完全不正确的数据建模方法。有效部门 ID 集受员工 ID 集约束是没有意义的。以这种方式定义外键还可以防止部门拥有超过 1 名员工。如果您真的在为部门和员工建模,您将向表中添加一DEPT_IDEMPLOYEE,该EMPLOYEE表将是子表,而不是父表,并且将在表上定义外键EMPLOYEE以引用该DEPARTMENT表。

于 2012-09-15T05:08:06.240 回答
1

我希望这可以帮助你

CREATE table "EMPLOYEE" (
"EMP_ID"     NUMBER,
"ENAME"      VARCHAR2(4000),
"SALARY"     VARCHAR2(4000),
"COMPANY"    VARCHAR2(4000),
"Dept_id"    NUMBER,
"CONTACTNO." NUMBER,
"GENDER"     CHAR(100),
 constraint  "EMPLOYEE_PK" primary key ("EMP_ID"),
 CONSTRAINT fk_DeptId FOREIGN KEY (Dept_Id)
 REFERENCES Department("Dept_Id") 
);
于 2012-09-15T04:22:27.167 回答
-1
CREATE table "EMPLOYEE" (
    "EMP_ID"     NUMBER,
    "ENAME"      VARCHAR2(4000),
    "SALARY"     VARCHAR2(4000),
    "COMPANY"    VARCHAR2(4000),
    "CONTACTNO"  NUMBER,
    "GENDER"     CHAR(100),
    constraint  "EMPLOYEE_PK" primary key ("EMP_ID")
)


ALTER TABLE "EMPLOYEE" ADD CONSTRAINT "EMPLOYEE_FK" 
FOREIGN KEY ("EMP_ID")
REFERENCES "DEPARTMENT" ("DEPT_ID")
于 2012-09-15T04:47:39.240 回答