33

错误:引用表 'dbo.Customers' 中没有与外键 'FK_Reservation_Customers_FrstNme FOREIGN KEY' 中的引用列列表匹配的主键或候选键

DROP TABLE dbo.Customers;
DROP TABLE dbo.Staff;
DROP TABLE dbo.Rooms;
DROP TABLE dbo.Reservation;
GO
CREATE TABLE "Customers"(

    CustomerID int IDENTITY (1,1) NOT NULL,
    FirstName nvarchar(20) NULL,
    LastName nvarchar(20) NULL,
    StreetNo int NULL,
    City nvarchar(20) NULL,
    PostCode nvarchar(20) NULL,
    Email nvarchar(50) NULL,

    CONSTRAINT PK_Customers PRIMARY KEY
    (
        CustomerID
    )
)
CREATE TABLE "Staff"(

    StaffID nvarchar(20) NOT NULL,
    Pass nvarchar(20) NOT NULL,

    CONSTRAINT PK_Staff PRIMARY KEY
    (
        StaffID
    )
)
CREATE TABLE "Rooms"(

    RoomNo int NOT NULL,
    RoomType nvarchar(20) NULL,
    PricePerNight money NULL,
    MaximumOccupancy int NULL,
    No0fBeds int NULL,
    NoOfBathrooms int NULL,
    Entertainment bit NULL,
    RoomService bit NULL,
    Gym bit NULL,

    CONSTRAINT PK_Rooms PRIMARY KEY
    (
        RoomNo
    )
)
CREATE TABLE "Reservation"(

    ReservationID int IDENTITY (1,1) NOT NULL,
    CustomerID int NOT NULL,
    FirstName nvarchar(20) NULL,
    LastName nvarchar(20) NULL,
    RoomType nvarchar(20) NULL,
    RoomNo int NOT NULL,
    CheckInDate date NULL,
    CheckOutDate date NULL,

    CONSTRAINT PK_Reservation PRIMARY KEY
    (
        ReservationID
    ),
    CONSTRAINT FK_Reservation_Customers_CustID FOREIGN KEY
    (
        CustomerID
    )   
        REFERENCES dbo.Customers
        (
            CustomerID
        ),
    CONSTRAINT FK_Reservation_Customers_FrstNme FOREIGN KEY
    (
        FirstName
    )
        REFERENCES dbo.Customers
        (
            FirstName
        )
    )

有人可以告诉我这里发生了什么以及如何解决它。我想制作外键的所有其他键都会出现同样的问题。除非我想引用主键。

4

2 回答 2

68

如果要创建外键,它必须引用主键或具有唯一约束的字段。

如果您想显示客户的姓名,请让外键引用 CustomerID,并通过连接显示结果。

于 2012-08-31T10:17:19.723 回答
7

当在引用表中指定与在引用表上定义主键或候选键的顺序不同的键列时,我遇到了这个错误。

切换指定列的顺序修复了它。

前任:

ALTER TABLE [dbo].[MCL_item_vendor_override_mst]  WITH CHECK ADD  
CONSTRAINT [FK_MCL_item_vendor_override_mst_item_mst] FOREIGN KEY([item],[site_ref])
    REFERENCES [dbo].[item_mst] ([item],[site_ref])

失败了

ALTER TABLE [dbo].[MCL_item_vendor_override_mst]  WITH CHECK ADD  
CONSTRAINT [FK_MCL_item_vendor_override_mst_item_mst] FOREIGN KEY([site_ref],[item])
    REFERENCES [dbo].[item_mst] ([site_ref],[item])

工作。

于 2017-08-11T21:19:02.757 回答