2016-07-26 344 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

谢谢你,它有很大帮助。我终于能够现在运行我的查询。 –