MySQL 外键不起作用
我在这里发布了一个问题,根据响应,我尝试创建以下 MySQL 表,但它不起作用,但是,如果我删除它的两个外部命令,它会起作用,
$query="CREATE TABLE IF NOT EXISTS picture(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID)
)ENGINE=InnoDB";
mysql_query($query,$con);
$query="CREATE TABLE IF NOT EXISTS user(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID)
)ENGINE=InnoDB";
mysql_query($query,$con);
$query="CREATE TABLE IF NOT EXISTS pictureRating
(
ID INT NOT NULL AUTO_INCREMENT,
pictureID INT NOT NULL,
userID INT NOT NULL,
rater INT NOT NULL,
creationDate TIMESTAMP DEFAULT NOW(),
context VARCHAR(150),
rating TINYINT,
PRIMARY KEY (ID),
FOREIGN KEY (pictureID) REFERENCES picture(ID) ON UPDATE CASCADE,
FOREIGN KEY (userID) REFERENCES user(ID) ON UPDATE CASCADE
)ENGINE=InnoDB";
mysql_query($query,$con)
我无法弄清楚为什么表无法创建
I posted a question here and as per the response I am trying to create the following MySQL table, but it does not work, however, if I remove the two foreign commands it works
$query="CREATE TABLE IF NOT EXISTS picture(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID)
)ENGINE=InnoDB";
mysql_query($query,$con);
$query="CREATE TABLE IF NOT EXISTS user(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID)
)ENGINE=InnoDB";
mysql_query($query,$con);
$query="CREATE TABLE IF NOT EXISTS pictureRating
(
ID INT NOT NULL AUTO_INCREMENT,
pictureID INT NOT NULL,
userID INT NOT NULL,
rater INT NOT NULL,
creationDate TIMESTAMP DEFAULT NOW(),
context VARCHAR(150),
rating TINYINT,
PRIMARY KEY (ID),
FOREIGN KEY (pictureID) REFERENCES picture(ID) ON UPDATE CASCADE,
FOREIGN KEY (userID) REFERENCES user(ID) ON UPDATE CASCADE
)ENGINE=InnoDB";
mysql_query($query,$con)
I can't figure out why the tables fail to get created
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在运行脚本之前,您需要删除所有三个表。
仅删除
pictureRating
表是不够的。您可能拥有前两个表的旧版本,这可能会导致第三个表的创建因外键约束而失败,但当您省略它们时会成功。当我删除所有三个表然后尝试运行命令时,它工作正常。
You need to drop all three tables before you run your script.
It's not enough just to drop the
pictureRating
table. You could have old versions of the first two tables which could cause the creation of the third table to fail with the foreign key constraints, but succeed when you omit them.When I delete all three tables and then try running your commands it works fine.