我不能在我的表中设置外键

时间:2017-12-13 12:21:05

标签: sql-server

显示

  

“引用的表'日期'中没有与外键'FK__SpecialAc__Itine__367C1819'中的引用列列表匹配的主键或候选键。   ”

create table Itinerary(
    ItineraryId int primary key identity,
    Description varchar(1000),
    TourId varchar(5)
    FOREIGN KEY (TourId) REFERENCES Tour(TourId)  
);

create table DatesInfo(
    Dates date NOT NULL,
    ItineraryId int NOT NULL,
    PlaceOfBreakfirst varchar(100) NOT NULL,
    PlaceOfLunch varchar(100) NOT NULL,
    PlaceOfDinner varchar(100) NOT NULL,
    PlaceOfAccommodation varchar(100) NOT NULL,
    Route varchar(1000) NOT NULL,
    ScheduleId int NOT NULL,
    PRIMARY KEY(Dates,ItineraryId),
    FOREIGN KEY (ScheduleId) REFERENCES Schedule(ScheduleId)  
);

create table SpecialActivity(
    Activity varchar(100),
    ItineraryId int NOT NULL,
    Dates date NOT NULL,
    PRIMARY KEY(Activity,ItineraryId,Dates),    
    FOREIGN KEY (ItineraryId) REFERENCES DatesInfo(ItineraryId),
    FOREIGN KEY (Dates) REFERENCES DatesInfo(Dates)         
);

1 个答案:

答案 0 :(得分:0)

您正在尝试创建两个单独的外键:

FOREIGN KEY (ItineraryId) REFERENCES DatesInfo(ItineraryId),
FOREIGN KEY (Dates) REFERENCES DatesInfo(Dates)

但是引用的表有一个(复合)主键:

PRIMARY KEY(Dates,ItineraryId),

外键需要匹配目标表中的主键。所以你需要一个复合外键:

FOREIGN KEY (Dates,ItineraryId) REFERENCES DatesInfo(Dates,ItineraryId),