我无法添加外键约束。我正在运行的sql是 -
ALTER TABLE image_shout ADD CONSTRAINT `fk_image` FOREIGN KEY (image_id)
REFERENCES images(image_id);
排序规则和数据类型(int(10))在两个表中相同。
mysql说 -
Error Code: 1215. Cannot add foreign key constraint
图像表结构 -
CREATE TABLE `images` (
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image_name` varchar(100) CHARACTER SET latin1 NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`caption` varchar(450) CHARACTER SET latin1 DEFAULT NULL,
`image_visibility` int(10) unsigned NOT NULL,
`album_id` int(10) unsigned NOT NULL,
`album_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`album_thumb_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`image_id`),
KEY `Index_2` (`album_id`),
CONSTRAINT `FK_images_1` FOREIGN KEY (`album_id`) REFERENCES `photo_album` (`Album_ID`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4314 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
image_shout表 -
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
更新 -
将image_id列更改为无符号后的新错误是 -
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
(`void`.`#sql-36b_7285`, CONSTRAINT `fk_image` FOREIGN KEY (`image_id`)
REFERENCES `images` (`image_id`) ON DELETE SET NULL ON UPDATE CASCADE)
此致
答案 0 :(得分:0)
问题如下。根据文档,必须索引外键。此外,外键应该引用另一个表的KEY。不只是一个专栏。如果您不想更改表格结构,请尝试使用auto_id作为约束。
Please see MySQL Documentation for the list of requirements of a Foreign Key constraint.
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
答案 1 :(得分:0)
是因为表格图片中的image_id
被定义为unsigned
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
并且在image_shout
中
`image_id` int(10) DEFAULT NULL,
将两列更改为相同的数据类型,它应该可以正常工作。