简体   繁体   English

SQL#1215-无法添加外键约束

[英]SQL #1215 - Cannot add foreign key constraint

I've got this code to create an SQL table, however I'm facing a #1215 error. 我已经有了这段代码来创建SQL表,但是我遇到了#1215错误。

CREATE TABLE ‘Categorie’ (
‘catID’ int(11) NOT NULL AUTO_INCREMENT,
‘naam’ varchar(20) NOT NULL,
‘prioriteit’ int(2) NOT NULL,
‘subCatVan’ int(11) DEFAULT NULL,
PRIMARY KEY (‘catID’),
CONSTRAINT ‘subCatVan’ FOREIGN KEY (‘subCatVan’) REFERENCES Categorie

(‘catID’) ON DELETE SET NULL ON UPDATE CASCADE
);

Help is appreciated! 感谢帮助!

As Jens already pointed out, there is an issue with your ticks. 正如Jens已经指出的那样,您的滴答声有问题。 First, the identifier quote character in MySQL is the backtick (`) by default, second, you are not using ticks for the table name in your foreign key constraint. 首先,在MySQL中的标识符引号字符是反引号(')在默认情况下,第二,你是不是使用蜱在您的外键约束的表名。

Replace all ticks with backticks and your statement will work (even without ticks around the table name in the foreign key constraint). 用反引号替换所有的滴答声,您的语句将起作用(即使在外键约束中表名周围也没有滴答声)。 Leave all ticks out and your statement will work. 撇开所有的勾号,您的陈述将起作用。 Change REFERENCES Categorie to REFERENCES 'Categorie' and your statement will work (although probably not as expected). 更改REFERENCES CategorieREFERENCES 'Categorie'和你的声明就可以了(虽然可能并不如预期)。

I would recommend using backticks in all places as a good practice: 我建议在所有地方都使用反引号作为一种好的做法:

CREATE TABLE `Categorie` (
`catID` int(11) NOT NULL AUTO_INCREMENT,
`naam` varchar(20) NOT NULL,
`prioriteit` int(2) NOT NULL,
`subCatVan` int(11) DEFAULT NULL,
PRIMARY KEY (`catID`),
CONSTRAINT `subCatVan` FOREIGN KEY (`subCatVan`) REFERENCES `Categorie`

(`catID`) ON DELETE SET NULL ON UPDATE CASCADE
);

What currently happens is that you are actually not creating a table named Categorie , but instead a table named 'Categorie' (including the ticks). 目前是什么情况是,你实际上没有创建一个名为表Categorie ,而是一个表名为'Categorie' (包括蜱)。 Because you are not using the same ticks in your foreign key constraint, MySQL looks for a table named Categorie without the ticks and thus cannot find the target for your reference. 因为你不使用你的外键约束相同的蜱中,MySQL查找一个名为表Categorie没有蜱虫,因而不能找到你的参考目标。

try this 尝试这个

CREATE TABLE `Categorie` (
`catID` INT(11) NOT NULL AUTO_INCREMENT,
`naam` VARCHAR(20) NOT NULL,
`prioriteit` INT(2) NOT NULL,
`subCatVan` INT(11) DEFAULT NULL,
PRIMARY KEY (`catID`),
CONSTRAINT `subCatVan` FOREIGN KEY (`subCatVan`) REFERENCES Categorie

(`catID`) ON DELETE SET NULL ON UPDATE CASCADE
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM