在SQL oracle中创建多个外键

时间:2017-10-02 13:11:52

标签: sql oracle

/* DROP TABLE STATEMENTS*/
DROP TABLE BUILDING CASCADE CONSTRAINTS PURGE;
DROP TABLE ROOM CASCADE CONSTRAINTS PURGE;
DROP TABLE SPEAKER CASCADE CONSTRAINTS PURGE;
DROP TABLE CONFERENCESESSION CASCADE CONSTRAINTS PURGE;

/* CREATE TABLE STATEMENTS*/
CREATE TABLE BUILDING(
BUILDINGNO CHAR(2),
BUILDINGWING VARCHAR2(15),
BUILDINGLANE VARCHAR2(15),
CONSTRAINT BUILDING_PK PRIMARY KEY(BUILDINGNO));

CREATE TABLE ROOM(
BUILDINGNO CHAR(2) ,
ROOMNO CHAR(2),
ROOMCAPACITY NUMBER(3), 
CONSTRAINT ROOM_PK PRIMARY KEY(BUILDINGNO, ROOMNO));

CREATE TABLE SPEAKER(
SPEAKERID CHAR(2),
SPEAKERNAME VARCHAR2(20),
SPEAKERADDRESS VARCHAR2(50),
SPEAKERPHONE CHAR(12),
CONSTRAINT SPEAKER_PK PRIMARY KEY(SPEAKERID));

CREATE TABLE CONFERENCESESSION(
SESSIONID CHAR(4) PRIMARY KEY,
BUILDINGNO CHAR(2) REFERENCES BUILDING(BUILDINGNO),
ROOMNO CHAR(2) REFERENCES ROOM(ROOMNO),
SPEAKERID CHAR(2) REFERENCES SPEAKER(SPEAKERID),
SESSIONDATE DATE,
SESSIONPRICE NUMBER(4, 2));

在最后一个表中,我应该有一个PK(SessionID)和3个外键(BuildingNo,RoomNo,SpeakerID),当我尝试这样做时,我得到没有匹配的主键? 有什么帮助吗?谢谢!

2 个答案:

答案 0 :(得分:1)

应该是:

CREATE   TABLE CONFERENCESESSION
(
   SESSIONID      CHAR (4) PRIMARY KEY,
   BUILDINGNO     CHAR (2)    ,
   ROOMNO         CHAR (2)    ,
   SPEAKERID      CHAR (2)    ,
   SESSIONDATE    DATE,
   SESSIONPRICE   NUMBER (4, 2),
   CONSTRAINT fk_blding  FOREIGN KEY (BUILDINGNO) REFERENCES BUILDING (BUILDINGNO),
   CONSTRAINT fk_roomno FOREIGN KEY  (BUILDINGNO,ROOMNO)REFERENCES ROOM (BUILDINGNO,ROOMNO),
   CONSTRAINT fk_spkr_id FOREIGN KEY (SPEAKERID)  REFERENCES SPEAKER (SPEAKERID)
);

答案 1 :(得分:0)

您只需要为3列添加此语法:

CONSTRAINT fk_supplier
FOREIGN KEY (column1)
REFERENCES parent_table (column1)

确保给予约束名称

E.G。

 constraint (Build_No)
 Foreign key (BUILDINGNO) 
 REFERENCES BUILDING(BUILDINGNO)

确保您实际使用其数据类型声明字段

CREATE TABLE CONFERENCESESSION
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
BUILDINGNO CHAR(2),            <--- declared here
constraint (Build_No)
Foreign key (BUILDINGNO) 
REFERENCES BUILDING(BUILDINGNO)
);

然后再对其他外键列重复此操作