2016-07-26 79 views
0

我有2個表,其中一個有2個外鍵,另一個有2個複合外鍵。每當我嘗試運行查詢時,它都會顯示錯誤,並且無法創建約束或索引。所以我在這裏有兩張桌子。如何在SQL Server的表中添加2個外鍵?

我知道我完全錯了,我對此表示歉意,因爲我對編碼有點陌生。

create table Booking 
(
    BookingID char(4) primary key, 
    dateBooked datetime not null, 
    creditCard char(16) null, 
    expiryDate datetime not null, 
    CVC char (3) not null, 
    confirmationID char(4) not null, 
    ticketType varchar(20) 
     foreign key references ticketType(ticketType), 
    NRIC char(9) 
     foreign key references Patron(NRIC) 
) 

create table BookingSeat 
(
    seatNo char(2) not null, 
    rowNo char(2) not null, 
    date datetime not null, 
    startTime time not null, 
    rowNo char(2) not null, 
    seatNo char(2) not null, 

    foreign key (date, startTime) 
     references hallSchedule(date, startTime), 
    foreign key (rowNo, seatNo) 
     references Seat(rowNo, seatNo) 
) 

回答

2

foreign key語法是:

FOREIGN KEY (addid) REFERENCES Table1_Addr(addid), 
FOREIGN KEY (id) REFERENCES Table1(id) 

對於表預訂。這是我已經注意到身份證應在表將其設置爲外鍵前:

CREATE TABLE BOOKING 
(BookingID char(4) primary key 
, dateBooked datetime not null 
, creditCard char(16) null 
, expiryDate datetime not null 
, CVC char (3) not null 
, confirmationID char(4) not null 
, ticketType varchar(20) 
, NRIC char(9)  
,FOREIGN KEY (ticketType) REFERENCES ticketType(ticketType) 
,FOREIGN KEY (NRIC) REFERENCES Patron(NRIC)) 

對於BookingSeat你沒有對這個表的主鍵?我注意到你定義了兩次seatNo。

CREATE TABLE BookingSeat 
(seatNo char(2) not null 
, rowNo char(2) not null 
, date datetime not null 
, startTime time not null 
, rowNo char(2) not null 
, FOREIGN KEY (date) REFERENCES hallSchedule(date) 
, FOREIGN KEY (startTime) REFERENCES hallSchedule(startTime) 
, FOREIGN KEY (rowNo) REFERENCES Seat(rowNo) 
, FOREIGN KEY (seatNo) REFERENCES Seat(seatNo)) 

請參閱這些鏈接引用: Can a table have two foreign keys? Multiple foreign keys?

+0

謝謝你,它有很大幫助。我終於能夠現在運行我的查詢。 –