我试图添加一个包含2列的外键。
以下是引用外键的表的DDL:
queue:work
拥有外键的表的DDL:
CREATE TABLE IF NOT EXISTS `sf_file_category` (
`id_file_category` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45)
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NOT NULL,
`file_type` ENUM('document', 'image', 'video', 'archive')
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NULL,
`id_file_category_parent` INT UNSIGNED NULL,
PRIMARY KEY (`id_file_category`),
INDEX `fk_sf_file_category_sf_file_category1_idx` (`id_file_category_parent` ASC),
INDEX `fk_sf_file_category_sf_file_idx` (`id_file_category` ASC, `file_type` ASC)
)
ENGINE = InnoDB;
尝试执行以下外键语法:
CREATE TABLE IF NOT EXISTS `sf_file` (
`id_file` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`fullpath` VARCHAR(100)
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NOT NULL,
`basename` VARCHAR(45)
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NOT NULL,
`accesskey` CHAR(8)
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NOT NULL,
`file_type` ENUM('document', 'image', 'video', 'archive')
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NULL,
`name` VARCHAR(45)
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NULL,
`description` VARCHAR(255)
CHARACTER SET 'latin1'
COLLATE 'latin1_general_ci' NULL,
`id_aircraft_image` SMALLINT UNSIGNED NULL,
`id_aircraft` SMALLINT UNSIGNED NULL,
`id_file_category` INT UNSIGNED NULL,
PRIMARY KEY (`id_file`),
INDEX `fk_sf_file_sf_file_category1_idx` (`id_file_category` ASC, `file_type` ASC),
INDEX `fk_sf_file_sf_aircraft1_idx` (`id_aircraft` ASC),
INDEX `fk_sf_file_sf_aircraft2_idx` (`id_aircraft_image` ASC)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1
COLLATE = latin1_general_ci;
但是我收到了这个错误: 错误:错误1822:无法添加外键constaint。缺少约束索引&f; fk_sf_file_sf_file_category1'在引用的表格中' sf_file_category'。
我认为他是指已在表sf_file_category中创建的INDEX ALTER TABLE `sf_file`
ADD CONSTRAINT `fk_sf_file_sf_file_category1`
FOREIGN KEY (`id_file_category` , `file_type`)
REFERENCES `sf_file_category` (`id_file_category` , `file_type`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
(fk_sf_file_sf_file_category1_idx
ASC,id_file_category
ASC)。
是否有任何特定方法可以创建我缺少的多个字段外键?
答案 0 :(得分:0)
就像提到的@Pankaj Pandey一样,我的字段声明不完全匹配,id_file_category
在表上是NULL
而在另一个表上NOT NULL
会阻止外键创建。