将复合主键和外键添加到一个表中的三列

时间:2018-02-18 18:44:32

标签: sql oracle foreign-keys primary-key composite-primary-key

问题: 创建一个名为REP_CONTRACTS的表,其中包含下表中列出的列。应分配包含REP_ID,STORE_ID和QUARTER列的复合PRIMARY KEY约束。此外,FOREIGN KEY约束应分配给REP_ID和STORE_ID列。

create table REP_CONTRACTS
(       STORE_ID    number(5) not null  
    ,   NAME        number(5)   
    ,   QUARTER     char(3)   not null      
    ,   REP_ID      number(5) not null  
);



alter table REP_CONTRACTS
add           constraint  FK_ID_STORE                foreign key(STORE_ID)
reference REP_CONTRACTS(STORE_ID)
add           constraint  FK_ID_REP                  foreign key(REP_ID)
reference REP_CONTRACTS(REP_ID) 
add           constraint  PK_REP_CONTRACTS           primary key(STORE_ID, REP_ID, QUARTER) 
reference REP_CONTRACTS(REP_ID, STORE_ID, QUARTER)
;

即使没有“非空”,我仍然得到相同的结果。我尝试添加带有和没有引用和约束的主键和外键,但我总是这样做。

Error starting at line : 618 in command -
alter table REP_CONTRACTS
add           constraint  FK_ID_STORE                foreign key(STORE_ID)                      
reference REP_CONTRACTS(STORE_ID)
add           constraint  FK_ID_REP                  foreign key(REP_ID)                        
reference REP_CONTRACTS(REP_ID)  
add           constraint  PK_REP_CONTRACTS           primary key(STORE_ID, 
REP_ID, QUARTER)     reference REP_CONTRACTS(REP_ID, STORE_ID, QUARTER)
Error report -
ORA-00905: missing keyword
00905. 00000 -  "missing keyword"
*Cause:    
*Action:

1 个答案:

答案 0 :(得分:1)

您应首先定义primary key(每个表可能存在一次)或unique keys,并使用关键字references代替reference,如下所示:

alter table REP_CONTRACTS add constraint  PK_REP_CONTRACTS primary key(STORE_ID, REP_ID, QUARTER);
alter table REP_CONTRACTS add constraint  PK_REP_CONTRACTS_ST unique(STORE_ID);
alter table REP_CONTRACTS add constraint  PK_REP_CONTRACTS_REP unique(REP_ID);

alter table REP_CONTRACTS add constraint  FK_ID_STORE  foreign key(STORE_ID) references REP_CONTRACTS(STORE_ID);
alter table REP_CONTRACTS add constraint  FK_ID_REP foreign key(REP_ID) references REP_CONTRACTS(REP_ID); 
alter table REP_CONTRACTS add constraint  FK_ID_REP_ST_QU foreign key(REP_ID, STORE_ID, QUARTER) references REP_CONTRACTS(REP_ID, STORE_ID, QUARTER);