[英]SQL : ERROR 1005: Can't create table 'obl2.itemsubjects' (errno: 121)
I have the following tables: 我有以下表格:
CREATE TABLE `OBL2`.`item` (
`itemID` INT NOT NULL AUTO_INCREMENT ,
`itemName` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`itemID`) ,
INDEX `itemName` (`itemName` ASC) );
CREATE TABLE `OBL2`.`subject` (
`subjectID` INT NOT NULL ,
`subjectName` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`subjectID`) );
Now since the connection is many to many, each item can have many subject and each subject can be related to many items - I'd like to set a connection table. 现在由于连接是多对多的,每个项目可以有很多主题,每个主题可以与许多项目相关 - 我想设置一个连接表。 This is my code: 这是我的代码:
CREATE TABLE `OBL2`.`itemsubjects` (
`itemID` INT NOT NULL ,
`subjectID` INT NOT NULL ,
PRIMARY KEY (`itemID`, `subjectID`) ,
INDEX `itemID_idx` (`itemID` ASC) ,
INDEX `subjectID_idx` (`subjectID` ASC) ,
CONSTRAINT `itemID`
FOREIGN KEY (`itemID` )
REFERENCES `OBL2`.`item` (`itemID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `subjectID`
FOREIGN KEY (`subjectID` )
REFERENCES `OBL2`.`subject` (`subjectID` )
ON DELETE CASCADE
ON UPDATE CASCADE);
but for some reason the code of the 3rd table is not being accepted. 但由于某种原因,第3表的代码未被接受。 I get an error message: 我收到一条错误消息:
ERROR 1005: Can't create table 'obl2.itemsubjects' (errno: 121) 错误1005:无法创建表'obl2.itemsubjects'(错误号:121)
I've read about the error on the internet and it says it's a known issue of MYSQL yet there are no solutions. 我已经读过互联网上的错误,它说它是MYSQL的已知问题,但没有解决方案。
Any thoughts? 有什么想法吗?
The MySQL docs say in FOREIGN KEY
Constraints (emphasis mine): MySQL文档在FOREIGN KEY
Constraints (强调我的)中说:
If the
CONSTRAINT
symbol clause is given, the symbol value must be unique in the database . 如果给出了CONSTRAINT
符号子句,则符号值在数据库中必须是唯一的 。 If the clause is not given, InnoDB creates the name automatically. 如果未给出该子句,InnoDB会自动创建名称。
So, the reason that the itemsubject
table creation failed, was that you had another (foreign key) constraint, named itemID
, or one named subjectID
in some other table of the database. 因此, itemsubject
表创建失败的原因是您有另一个(外键)约束,名为itemID
,或者在数据库的某个其他表中有一个名为subjectID
约束。
It's good to have a naming conevntion that is standard across the database. 在整个数据库中使用标准命名是很好的。 Just as you have ColumnName_idx
for indices, you can use ReferencedTable_ReferencingTable_FK
for foreign key constraints: 就像索引的ColumnName_idx
,您可以将ReferencedTable_ReferencingTable_FK
用于外键约束:
CREATE TABLE OBL2.itemsubjects (
itemID INT NOT NULL ,
subjectID INT NOT NULL ,
PRIMARY KEY
(itemID, subjectID) ,
INDEX itemID_idx -- I like these
(itemID ASC) ,
INDEX subjectID_idx -- two
(subjectID ASC) ,
CONSTRAINT item_itemsubject_FK -- what I propose, here
FOREIGN KEY (itemID)
REFERENCES OBL2.item (itemID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT subject_itemsubject_FK -- and here
FOREIGN KEY (subjectID)
REFERENCES OBL2.subject (subjectID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.