开发者社区> 问答> 正文

无法删除或更新父行:外键约束失败

进行时:

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);

展开
收起
保持可爱mmm 2020-05-11 10:31:29 535 0
1 条回答
写回答
取消 提交回答
  • 照原样,必须先删除Advertisers表中的行,然后才能删除它引用的Jobs表中的行。这个:

    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); 纠正外键关系后,您的delete语句将起作用。来源:stack overflow

    2020-05-11 10:31:44
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载