MySQL:非重复密钥的重复密钥错误1022
我试图创建一个具有不同外键约束的表,但mysql抱怨这个DDL:MySQL:非重复密钥的重复密钥错误1022,mysql,foreign-keys,constraints,percona,Mysql,Foreign Keys,Constraints,Percona,我试图创建一个具有不同外键约束的表,但mysql抱怨这个DDL: CREATE TABLE tasks ( id INTEGER NOT NULL AUTO_INCREMENT, `createdAt` DATETIME NOT NULL DEFAULT now(), `updatedAt` DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW(), `createdBy_user_id`
CREATE TABLE tasks (
id INTEGER NOT NULL AUTO_INCREMENT,
`createdAt` DATETIME NOT NULL DEFAULT now(),
`updatedAt` DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW(),
`createdBy_user_id` INTEGER NOT NULL,
`updatedBy_user_id` INTEGER NOT NULL,
status ENUM('open','closed') NOT NULL,
customer_id INTEGER NOT NULL,
`projectDescription` TEXT,
PRIMARY KEY (id),
CONSTRAINT user_id_fk FOREIGN KEY(`createdBy_user_id`) REFERENCES users (id),
CONSTRAINT customer_id_fk FOREIGN KEY(customer_id) REFERENCES `Customer` (id),
CONSTRAINT user_up_id_fk FOREIGN KEY(`updatedBy_user_id`) REFERENCES users (id)
)COLLATE utf8mb4_german2_ci CHARSET=utf8mb4
我得到错误错误1022(23000):无法写入;表'tasks'
中的重复键没有意义,因为每个约束都有不同的名称,并且应用于不同的列
奇怪的是,如果我删除fk
-后缀并用类似constr
的东西替换它,MySQL不会抱怨
有人知道为什么MySQL 5.7(
服务器版本:5.7.30-33 Percona Server(GPL),Release 33,Revision 6517692
)的行为是这样的吗?您在另一个表中使用了具有相同名称的约束
这是一种很容易重现此问题的方法:
CREATE TABLE foo
(
id int not null auto_increment primary key
);
CREATE TABLE bar
(
id int not null auto_increment primary key,
foo_id int,
CONSTRAINT foo_id_fk FOREIGN KEY(`foo_id`) REFERENCES foo(id) -- <- Check this constraint name
);
CREATE TABLE hello
(
id int not null auto_increment primary key,
foo_id int,
CONSTRAINT foo_id_fk FOREIGN KEY(`foo_id`) REFERENCES foo(id) -- <-- same constraint name than before
);
或者你可以用一个我不能。你确定这是你的密码吗?是的。它由数据库迁移工具生成,并产生此错误。也许我应该提到我使用的是
服务器版本:5.7.30-33 Percona Server(GPL),发行版33,修订版6517692
谢谢,来自服务器的错误消息确实令人误解,因为它让您认为问题是同一个表中的两个相等键。
-- v----------- no name here
CONSTRAINT FOREIGN KEY(`createdBy_user_id`) REFERENCES users (id)