需要帮助创建外键sql error 1215

时间:2017-01-20 11:05:22

标签: mysql database reference

您好我的帮助请求,但我在添加引用的数据库中遇到了一些问题

所以我有一张桌子

CREATE TABLE `kooien` (
`kooiid` INT(11) NOT NULL AUTO_INCREMENT,
`kooidlistppg` INT(11) NULL,
`quarantaine` BIT(1) NOT NULL,
`idvogelsoort` INT(11) NULL DEFAULT NULL,
`idvogelondersoort` INT(11) NULL DEFAULT NULL,
`vasteoflossekooie` BIT(1) NOT NULL,
`bezetofniet` BIT(1) NOT NULL,
`idlistsponsor` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`kooiid`),
INDEX `idvogelsoort` (`idvogelsoort`),
INDEX `idvogelondersoort` (`idvogelondersoort`),
INDEX `kooien_ibfk_4_idx` (`idlistsponsor`),
CONSTRAINT `kooien_ibfk_2` FOREIGN KEY (`idvogelsoort`) REFERENCES `vogelsoort` (`id`),
CONSTRAINT `kooien_ibfk_3` FOREIGN KEY (`idvogelondersoort`) REFERENCES `ondersoort` (`id`),
CONSTRAINT `kooien_ibfk_4` FOREIGN KEY (`idlistsponsor`) REFERENCES `personen` (`id`),
CONSTRAINT `FK_kooien_kooientoppg` FOREIGN KEY (`kooidlistppg`) REFERENCES `kooientoppg` (`id`))
COLLATE='utf8_general_ci'
ENGINE=InnoDB

看起来像

kooiid|kooidlistppg|quarantaine|idvogelsoort|idvogelondersoort|Vasteoflossekooien|bezetofniet|lijstlist sponsor

现在我的问题是将kooidlistppg引用到kooidlistppg(id) 我使用此查询

ALTER TABLE `kooien`
DROP INDEX `FK_kooien_kooientoppg`,
ADD CONSTRAINT `FK_kooien_kooientoppg` FOREIGN KEY (`kooidlistppg`) REFERENCES `kooientoppg` (`id`);
/* SQL Fout (1215): Cannot add foreign key constraint */

为表添加创建查询

CREATE TABLE `kooientoppg` (
`id` INT(11) NOT NULL,
`idpapegaaien` INT(11) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB

请知道它缺少主键是将列表转换为mysql数据库

1 个答案:

答案 0 :(得分:0)

MySQL manual中所述,可以使用以下SQL命令检查InnoDB的FOREIGN KEY错误的详细信息:

SHOW ENGINE INNODB STATUS

例如:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2017-01-22 23:43:46 0x7fc9fc0f1700 Error in foreign key constraint of table test/kooien:
 FOREIGN KEY (`kooidlistppg`) REFERENCES `kooientoppg` (`id`))
 COLLATE='utf8_general_ci'
 ENGINE=InnoDB:
 Cannot find an index in the referenced table where the
 referenced columns appear as the first columns, or column types
 in the table and the referenced table do not match for constraint.
 Note that the internal storage type of ENUM and SET changed in
 tables created with >= InnoDB-4.1.12, and such columns in old tables
 cannot be referenced by such columns in new tables.
 Please refer to http://dev.mysql.com/doc/refman/8.0/en/innodb-foreign-key-constraints.html for correct foreign key definition.

据我所知,在引用列中添加索引会有所帮助:

ALTER TABLE kooientoppg ADD INDEX id_idx (id);