无法删除或更新父行:外键约束失败做的时候:DELETE FROM `jobs` WHERE `job_id` =1 LIMIT 1它错误:#1451 - Cannot delete or update a parent row: a foreign key constraint fails
(paymesomething.advertisers, CONSTRAINT advertisers_ibfk_1 FOREIGN KEY (advertiser_id) REFERENCES jobs (advertiser_id))这是我的表格:CREATE TABLE IF NOT EXISTS `advertisers` (
`advertiser_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`password` char(32) NOT NULL,
`email` varchar(128) NOT NULL,
`address` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`fax` varchar(255) NOT NULL,
`session_token` char(30) NOT NULL,
PRIMARY KEY (`advertiser_id`),
UNIQUE KEY `email` (`email`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;INSERT INTO `advertisers` (`advertiser_id`, `name`, `password`, `email`, `address`, `phone`, `fax`, `session_token`) VALUES(1, 'TEST COMPANY', '', '', '', '', '', '');CREATE TABLE IF NOT EXISTS `jobs` (
`job_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`advertiser_id` int(11) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`shortdesc` varchar(255) NOT NULL,
`longdesc` text NOT NULL,
`address` varchar(255) NOT NULL,
`time_added` int(11) NOT NULL,
`active` tinyint(1) NOT NULL,
`moderated` tinyint(1) NOT NULL,
PRIMARY KEY (`job_id`),
KEY `advertiser_id` (`advertiser_id`,`active`,`moderated`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;INSERT INTO `jobs` (`job_id`, `advertiser_id`, `name`, `shortdesc`, `longdesc`, `address`, `active`, `moderated`) VALUES(1, 1, 'TEST', 'TESTTEST', 'TESTTESTES', '', 0, 0);ALTER TABLE `advertisers`
ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `jobs` (`advertiser_id`);
3 回答
慕仙森
TA贡献1827条经验 获得超7个赞
按原样,您必须先删除广告商表中的行,然后才能删除它引用的作业表中的行。这个:
ALTER TABLE `advertisers` ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `jobs` (`advertiser_id`);
......实际上与应该是的相反。实际上,这意味着您必须在广告商之前在作业表中创建记录。所以你需要使用:
ALTER TABLE `jobs` ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `advertisers` (`advertiser_id`);
一旦纠正了外键关系,你的删除语句就可以了。
慕姐8265434
TA贡献1813条经验 获得超2个赞
简单的方法是禁用外键检查; 进行更改然后重新启用外键检查。
SET FOREIGN_KEY_CHECKS=0; -- to disable them
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them
慕村9548890
TA贡献1884条经验 获得超4个赞
在您当前(可能有缺陷的)设计下,您必须先删除广告商表中的行,然后才能删除它引用的作业表中的行。
或者,您可以设置外键,以便父表中的删除会导致子表中的行自动删除。这称为级联删除。它看起来像这样:
ALTER TABLE `advertisers`ADD CONSTRAINT `advertisers_ibfk_1`FOREIGN KEY (`advertiser_id`) REFERENCES `jobs` (`advertiser_id`)ON DELETE CASCADE;
话虽如此,正如其他人已经指出的那样,你的外键感觉它应该反过来,因为广告商表真的包含主键而job表包含外键。我会像这样重写它:
ALTER TABLE `jobs`ADD FOREIGN KEY (`advertiser_id`) REFERENCES `advertisers` (`advertiser_id`);
并且不需要级联删除。
添加回答
举报
0/150
提交
取消