首先,我已经阅读了有关此类错误类型的所有StackOverflow问题,我无法理解为什么会出现此错误。
我有一个meetings
表:
CREATE TABLE `meetings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` text,
`city` varchar(255) DEFAULT NULL,
`start_time` datetime DEFAULT NULL,
`end_time` datetime DEFAULT NULL,
`owner` varchar(128) NOT NULL,
`is_private` tinyint(1) DEFAULT NULL,
`priority` int(11) DEFAULT NULL,
`accepted_count` int(11) DEFAULT NULL,
`creation_time` datetime DEFAULT CURRENT_TIMESTAMP,
`main_pic` text,
PRIMARY KEY (`id`),
KEY `user_id_idx` (`owner`),
KEY `city_fk_idx` (`city`),
KEY `weight_idx` (`priority`),
CONSTRAINT `city_fk` FOREIGN KEY (`city`) REFERENCES `cities` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `user_id` FOREIGN KEY (`owner`) REFERENCES `users` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `weight` FOREIGN KEY (`priority`) REFERENCES `priorities` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
我还有meeting_pictures
表
CREATE TABLE `meeting_pictures` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`path` text NOT NULL,
`meeting_id` int(11) NOT NULL,
`user_id` varchar(128) NOT NULL,
PRIMARY KEY (`id`,`meeting_id`),
KEY `user_id_idx` (`user_id`),
CONSTRAINT `user_id_fkk` FOREIGN KEY (`user_id`) REFERENCES `users` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
这就是我尝试添加新FK的方式:
ALTER TABLE `tts`.`meetings`
ADD CONSTRAINT `meeting_pic_fk1`
FOREIGN KEY (`id`)
REFERENCES `tts`.`meeting_pictures` (`meeting_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
每次我都有:“ERROR 1215:无法添加外键约束”。为什么会这样?两列的类型相同。我怎样才能添加这样的FK?
由于
答案 0 :(得分:1)
meeting_pictures
上的主键由两部分组成:meeting_id
和id
。如果我不得不猜测,你打算让外键约束转向另一个方向:
ALTER TABLE tts.meeting_pictures
ADD CONSTRAINT meeting_pic_fk1
FOREIGN KEY (meeting_id)
REFERENCES tts.meetings (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
至少,tts.meeting_picures(meeting_id)
引用tts.meetings(id)
对我有意义。