Mysql 主外键报错:Error 'Cannot add or update a child row: a foreign key constraint fails

参考博客:http://blog.csdn.net/garcon1986/article/details/5337336

1、报错:Error 'Cannot add or update a child row: a foreign key constraint fails (bsppr.xentry, CONSTRAINT fk_res_facet FOREIGN KEY (facetid) REFERENCES xfacet (id) ON DELETE CASCADE ON UPDATE CASCADE)' on query. Default database: 'bsppr'. Query: 'INSERT INTO xentry (date, facetid) VALUES ('2018-02-25', 94098)'

2、切换到库
mysql> use bsppr;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

3、查看表结构
mysql> mysql> show create table xentryG
*************************** 1. row ***************************
Table: xentry
Create Table: CREATE TABLE xentry (
entryid int(10) unsigned NOT NULL AUTO_INCREMENT,
facetid int(11) NOT NULL,
date date NOT NULL,
docs1 int(11) NOT NULL DEFAULT '0',
docs2 int(11) NOT NULL DEFAULT '0',
docs3 int(11) NOT NULL DEFAULT '0',
post1 int(11) NOT NULL DEFAULT '0',
post2 int(11) NOT NULL DEFAULT '0',
post3 int(11) NOT NULL DEFAULT '0',
click int(11) NOT NULL DEFAULT '1',
lastupdatetime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (entryid),
UNIQUE KEY idx_date (facetid,date),
KEY fk_res_facet (facetid),
KEY idx_date_s (date),
CONSTRAINT fk_res_facet FOREIGN KEY (facetid) REFERENCES xfacet (id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=85528322 DEFAULT CHARSET=utf8
1 row in set (2.74 sec)

=====================================================
3.1 alter table xentry drop foreign key fk_res_facet; #删除外键

3.2 alter table xentry add foreign key (facetid) references xfacet (id) on delete cascade on update cascade; #添加外键

3.3 INSERT INTO xentry (date, facetid) VALUES ('2018-02-25', 94098); #执行语句

原文地址:https://www.cnblogs.com/fengmeng1030/p/8479817.html