我正在尝试创建一个包含很少表的模式。
我尝试过运行此脚本,但我收到了错误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)
);
答案 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));
基本上这一行
FOREIGN KEY (prankId) REFERENCES Prank(prankId)
正在创建问题,即您需要首先创建Prank
表,因为您在Review
表中引用了它的列。