如何在创建模式时解决外键约束错误

时间:2015-04-14 10:19:55

标签: mysql sql key constraints

我正在尝试创建一个包含很少表的模式。 我尝试过运行此脚本,但我收到了错误cannot add foreign key constraint。我找不到问题,

CREATE TABLE User
(
    email VARCHAR(32) NOT NULL,
    name VARCHAR(32) NOT NULL,
    password VARCHAR(32) NOT NULL,
    dateOfBirth DATE NOT NULL,
    PRIMARY KEY(email)
);

CREATE TABLE Review
(
    reviewId INT NOT NULL AUTO_INCREMENT,
    email VARCHAR(32) NOT NULL,
    prankId INT,
    rating INT,
    comment VARCHAR(1056) NOT NULL,
    PRIMARY KEY(reviewId),
    FOREIGN KEY (email) REFERENCES User(email) ON UPDATE CASCADE,
    FOREIGN KEY (prankId) REFERENCES Prank(prankId)
);

CREATE TABLE Prank
(
    prankId INT AUTO_INCREMENT,
    prankName VARCHAR(32) NOT NULL,
    description VARCHAR(1056) NOT NULL,
    price DECIMAL(18,4) NOT NULL,
    PRIMARY KEY(prankId)
);

2 个答案:

答案 0 :(得分:1)

在创建Prank之前,只需为Review使用CREATE TABLE。因此Review可以在创建Prank之后引用{{1}},并且可以知道您要求字段引用哪个表和该表的哪个字段。

答案 1 :(得分:0)

试试这个:

CREATE TABLE User
(
email VARCHAR(32) NOT NULL,
name VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL,
dateOfBirth DATE NOT NULL,
PRIMARY KEY(email)
);

CREATE TABLE Prank
(
prankId INT AUTO_INCREMENT,
prankName VARCHAR(32) NOT NULL,
description VARCHAR(1056) NOT NULL,
price DECIMAL(18,4) NOT NULL,
PRIMARY KEY(prankId)
);

CREATE TABLE Review
(
reviewId INT NOT NULL AUTO_INCREMENT,
email VARCHAR(32) NOT NULL,
prankId INT,
rating INT,
comment VARCHAR(1056) NOT NULL,
PRIMARY KEY(reviewId),
FOREIGN KEY (email) REFERENCES User(email) ON UPDATE CASCADE,
FOREIGN KEY (prankId) REFERENCES Prank(prankId));

SQL FIDDLE DEMO

基本上这一行

FOREIGN KEY (prankId) REFERENCES Prank(prankId)

正在创建问题,即您需要首先创建Prank表,因为您在Review表中引用了它的列。