复合外键 - 可能在Oracle中?

时间:2011-12-08 16:24:14

标签: sql database oracle

我正在尝试在Oracle中创建一个介于两个多对多表之间的关系/表,因此该表的主键是复合键,但这两个键都是外来的。

CREATE TABLE employee_licence_certificate(
    emp_id NUMBER(4) REFERENCES employee(emp_id)
    , licence_cert_code VARCHAR2(6) REFERENCES licence_certificate(licence_cert_code)
    , date_earned DATE NOT NULL
    ) 
PRIMARY KEY (emp_id, licence_cert_code))

我尝试过使用合成键的方法,但我似乎得到了以下错误,这让我想知道这是否可能?

Error starting at line 1 in command:
CREATE TABLE employee_licence_certificate(emp_id NUMBER(4) REFERENCES employee(emp_id)
, licence_cert_code VARCHAR2(6) REFERENCES licence_certificate(licence_cert_code)
, date_earned DATE NOT NULL) PRIMARY KEY (emp_id, licence_cert_code))
Error at Command Line:3 Column:29
Error report:
SQL Error: ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:    
*Action:

3 个答案:

答案 0 :(得分:4)

试试这个:

CREATE TABLE employee_licence_certificate(
    emp_id NUMBER(4) REFERENCES employee(emp_id)
  , licence_cert_code VARCHAR2(6) REFERENCES licence_certificate(licence_cert_code)
  , date_earned DATE NOT NULL
  ,
PRIMARY KEY (emp_id, licence_cert_code))

答案 1 :(得分:4)

我使用不同的语法。我更喜欢明确地命名我的外键约束,以便错误消息if / when违反时更有意义/可追踪。所以我会这样做:

CREATE TABLE employee_licence_certificate
(   emp_id              NUMBER(4)   NOT NULL
,   licence_cert_code   VARCHAR2(6) NOT NULL
,   date_earned         DATE        NOT NULL
,   CONSTRAINT elc_pk PRIMARY KEY (emp_id, licence_cert_code)
,   CONSTRAINT elc_emp_fk FOREIGN KEY (emp_id)
        REFERENCES employee(emp_id)
,   CONSTRAINT elc_lct_fk FOREIGN KEY (licence_cert_code )
        REFERENCES licence_certificate(licence_cert_code)
)

答案 2 :(得分:2)

确定有可能。你只需要修改你的陈述:

CREATE TABLE employee_licence_certificate(emp_id NUMBER(4) REFERENCES employee(emp_id)
, licence_cert_code VARCHAR2(6) REFERENCES licence_certificate(licence_cert_code)
, date_earned DATE NOT NULL, PRIMARY KEY (emp_id, licence_cert_code))

顺便说一下,在正确格式化语句时,更容易发现这些错误:

create table employee_licence_certificate
(
  emp_id number(15) references employee(emp_id),
  licence_cert_code VARCHAR2(6) REFERENCES licence_certificate(licence_cert_code),
  date_earned date not null,
  primary key (emp_id, licence_cert_code)
)
相关问题