当我尝试将THIRD外键添加到我的表时,无法添加外键约束错误

时间:2016-03-12 20:28:17

标签: mysql foreign-keys create-table

我一直在尝试将属性 O_BagelID 添加到我的<form id="startTest" method="POST" action=""> <input type="hidden" name="answer" value="startTest"> <input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br> <input type="submit" name="submit" value="Start test"> 表中,但每当我尝试添加它时,我都会收到错误&#34;无法添加外键约束& #34;

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

Order

1 个答案:

答案 0 :(得分: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  
);