gpt4 book ai didi

mysql - 在两个表 : Why? 的非常简单的情况下,MySQL 5.6.16 中的 "Cannot add foreign key constraint"错误

转载 作者:可可西里 更新时间:2023-11-01 11:28:59 25 4
gpt4 key购买 nike

这是我尝试执行的确切 SQL(在 Windows 上使用 SQLYog 作为 MySQL 客户端):

DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` INT (11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE = INNODB ;

DROP TABLE IF EXISTS `temp`;
CREATE TEMPORARY TABLE `temp` (
dish_id INT (11) NOT NULL,
user_id INT (11) NOT NULL,
UNIQUE KEY (dish_id, user_id),
FOREIGN KEY `test` (dish_id) REFERENCES test (id)
) ENGINE = INNODB ;

这是在尝试创建 temp 时收到的确切错误:

Error Code: 1215
Cannot add foreign key constraint

在我看来一切都井井有条——两个相关 key 的数据类型和签名是相同的;这些名字似乎是犹太洁食;这是怎么回事?

我做错了什么?为什么创建外键约束失败?

最佳答案

这是因为您要向临时表添加外键约束。

来自手册:

Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. The parent and child tables must use the same storage engine. They must not be TEMPORARY tables.

http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html

编辑:尝试使用永久表。它有效。

DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` INT (11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE = INNODB ;

DROP TABLE IF EXISTS `temp`;
CREATE TABLE `temp` (
dish_id INT (11) NOT NULL,
user_id INT (11) NOT NULL,
UNIQUE KEY (dish_id, user_id),
FOREIGN KEY `test` (dish_id) REFERENCES test (id)
) ENGINE = INNODB ;

关于mysql - 在两个表 : Why? 的非常简单的情况下,MySQL 5.6.16 中的 "Cannot add foreign key constraint"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25658497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com