我有一个名为子类别的表,其记录可以进一步链接到表中的其他记录。所以我创建了一个subcategorylinker
表来定义这些链接。在此表中,我有2列子类别和nextsubcategory
,两者都引用子类别表的id字段。但是我在创建表时遇到错误。错误如下:
ERROR 1005: Can't create table 'test01.subcategorylinker' (errno: 150)
表定义如下:
CREATE TABLE `test01`.`subcategorylinker` (
`id` INT NOT NULL ,
`subcategory` INT NOT NULL ,
`nextsubcategory` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_subcategorylinker_sub` (`subcategory` ASC, `nextsubcategory` ASC) ,
CONSTRAINT `fk_subcategorylinker_sub`
FOREIGN KEY (`subcategory` , `nextsubcategory` )
REFERENCES `test01`.`subcategories` (`id` , `id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION);
答案 0 :(得分:1)
让我们检查外键条款:
FOREIGN KEY (`subcategory` , `nextsubcategory` )
REFERENCES `test01`.`subcategories` (`id` , `id` )
这意味着表格中(subcategory, nextsubcategroy)
的每个组合都应与表格中(id, id)
的组合相匹配。由于没有(id, id)
的组合,因为它是单个字段,因此该声明是非法的。
相反,您可以有两个外键,subcategory
和nextsubcategory
一个,每个都应与id
匹配:
CREATE TABLE `test01`.`subcategorylinker` (
`id` INT NOT NULL ,
`subcategory` INT NOT NULL ,
`nextsubcategory` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_subcategorylinker_sub` (`subcategory` ASC),
CONSTRAINT `fk_subcategorylinker_sub`
FOREIGN KEY (`subcategory`)
REFERENCES `test01`.`subcategories` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
INDEX `fk_nextsubcategorylinker_sub` (`nextsubcategory` ASC),
CONSTRAINT `fk_nextsubcategorylinker_sub`
FOREIGN KEY (`nextsubcategory`)
REFERENCES `test01`.`subcategories` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);