gpt4 book ai didi

mysql 无法添加外键,原因不明

转载 作者:行者123 更新时间:2023-11-30 00:02:21 24 4
gpt4 key购买 nike

我无法添加外键约束。我正在运行的 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)

问候

最佳答案

是因为表格图像中的image_id被定义为unsigned

`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,

而在image_shout中则不然

`image_id` int(10) DEFAULT NULL,

将两列更改为相同的数据类型,它应该可以工作。

关于mysql 无法添加外键,原因不明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com