无法使用复合键作为外键

时间:2015-10-28 12:35:53

标签: oracle

CREATE TABLE departments
( department_id number(10) NOT NULL,
  department_name varchar2(50) NOT NULL,
  department_code varchar2(50) NOT NULL,
  CONSTRAINT departments_pk PRIMARY KEY (department_id, department_code)
);

CREATE TABLE employees
( employee_number number(10) NOT NULL,
  employee_name varchar2(50) NOT NULL,
  department_id number(10),
  salary number(6),
  CONSTRAINT employees_pk PRIMARY KEY (employee_number),
  CONSTRAINT fk_departments
    FOREIGN KEY (department_id, department_code)
    REFERENCES departments(department_id,department_code));

1 个答案:

答案 0 :(得分:1)

您的employees表格没有department_code字段,因此FOREIGN KEY (department_id, department_code)部分正在尝试使用不存在的内容。运行第二个语句时出现的错误是:

ERROR at line 8:
ORA-00904: "DEPARTMENT_CODE": invalid identifier

您要么必须在该表中包含部门代码,这会使数据非规范化;或者将departments上的主键更改为department_id,这无论如何都会更正常,即:

CREATE TABLE departments
( department_id number(10) NOT NULL,
  department_name varchar2(50) NOT NULL,
  department_code varchar2(50) NOT NULL,
  CONSTRAINT departments_pk PRIMARY KEY (department_id)
);

CREATE TABLE employees
( employee_number number(10) NOT NULL,
  employee_name varchar2(50) NOT NULL,
  department_id number(10),
  salary number(6),
  CONSTRAINT employees_pk PRIMARY KEY (employee_number),
  CONSTRAINT fk_departments
    FOREIGN KEY (department_id)
    REFERENCES departments(department_id));

拥有像这样的复合主键通常没有意义,其中只有一列看起来应该是唯一的。您不会期望具有两个department_id值的department_code {/ p>}。

但是如果你有合法的理由拥有复合主键,那么该键中的所有列都必须在子表及其外键约束上重复:

CREATE TABLE employees
( employee_number number(10) NOT NULL,
  employee_name varchar2(50) NOT NULL,
  department_id number(10),
  department_code varchar2(50) NOT NULL,
  salary number(6),
  CONSTRAINT employees_pk PRIMARY KEY (employee_number),
  CONSTRAINT fk_departments
    FOREIGN KEY (department_id, department_code)
    REFERENCES departments(department_id,department_code));

Table EMPLOYEES created.

这意味着无论何时将记录插入该表,您都必须提供现有部门的ID和代码。