当我尝试向我的 table 添加第三个外键时出现无法添加外键约束错误

Cannot add foreign key constraint error occurs when I try to add a THIRD Foreign Key to my table

我一直在尝试将属性 O_BagelID 添加到我的 Order Table 中,但是每当我尝试添加它时,我收到错误 "Cannot add foreign key constraint".

如您所见,我已确保 Order 中的外键和 Bagel 中的引用属于同一类型。当我删除 O_BagelID 和所有相关字段时,我不再收到该错误。

CREATE TABLE `Order`(
    OrderID INTEGER NOT NULL, 
    O_CustomerID INTEGER NOT NULL,  
    O_BagelCardID VARCHAR(16),
    O_BagelID INTEGER,  
    Order_date DATE NOT NULL, 
    Order_Cost DECIMAL(4,2) NOT NULL,
    Discount_applied BOOLEAN NOT NULL, 
    PRIMARY KEY(OrderID,O_CustomerID,O_BagelCardID,O_BagelID),

    FOREIGN KEY (O_CustomerID) 
    REFERENCES Customer(CustomerID)
    ON DELETE RESTRICT
    ON UPDATE CASCADE,

    FOREIGN KEY (O_BagelCardID) 
    REFERENCES BagelCard(BagelCardID)
    ON DELETE RESTRICT
    ON UPDATE CASCADE,

    FOREIGN KEY (O_BagelID) 
    REFERENCES Bagel(BagelID)
    ON DELETE RESTRICT
    ON UPDATE CASCADE  
);

CREATE TABLE Bagel(
    BagelID INTEGER NOT NULL,
    Contains_Nuts BOOLEAN NOT NULL,
    Price DECIMAL(4,2) NOT NULL, 
    Description VARCHAR(255),
    PRIMARY KEY(BagelID)
);

您应该先创建 table Bagel,然后再创建 table Order。当您创建对另一个 table 的引用时,它应该已经存在:

CREATE TABLE Bagel(
    BagelID INTEGER NOT NULL,
    Contains_Nuts BOOLEAN NOT NULL,
    Price DECIMAL(4,2) NOT NULL, 
    Description VARCHAR(255),
    PRIMARY KEY(BagelID)
);

CREATE TABLE `Order`(
    OrderID INTEGER NOT NULL, 
    O_CustomerID INTEGER NOT NULL,  
    O_BagelCardID VARCHAR(16),
    O_BagelID INTEGER,  
    Order_date DATE NOT NULL, 
    Order_Cost DECIMAL(4,2) NOT NULL,
    Discount_applied BOOLEAN NOT NULL, 
    PRIMARY KEY(OrderID,O_CustomerID,O_BagelCardID,O_BagelID),

    FOREIGN KEY (O_CustomerID) 
    REFERENCES Customer(CustomerID)
    ON DELETE RESTRICT
    ON UPDATE CASCADE,

    FOREIGN KEY (O_BagelCardID) 
    REFERENCES BagelCard(BagelCardID)
    ON DELETE RESTRICT
    ON UPDATE CASCADE,

    FOREIGN KEY (O_BagelID) 
    REFERENCES Bagel(BagelID)
    ON DELETE RESTRICT
    ON UPDATE CASCADE  
);