2016-03-12 43 views
0

我一直在試圖增加O_BagelID到我Order表的屬性,但是每當我嘗試添加它,我得到的錯誤「無法添加外鍵約束」。無法添加外鍵約束髮生錯誤時,我嘗試第三外鍵添加到我的表

正如你可以看到我已經確信,無論是外鍵,以便和在百吉餅的參考是同一類型的。當我刪除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) 
); 
+0

添加錯誤消息 – Jens

+0

「無法添加外鍵約束」。這就是我得到的。 – LovesPie

+0

創建http://sqlfiddle.com/請 – Jens

回答

0

您應該創建表Bagel第一,然後創建表Order。當您創建REFERENCES到另一個表時,它應該已經存在:

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 
);