我的 table1
有 3 列:id varchar(20)
、name
、mother_id varchar(20)
。 mother_id
是引用同一个表中 id
列的外键。
这是我的表格:
|id |name |mother_id|
|dog1 |my_dog | (null)
|dog2 |my_dog2 | dog1
|dog3 |my_dog3 | dog1
如果我尝试更新 dog1
并更改 dog4
,则会出现此错误:
Cannot delete or update a parent row: a foreign key constraint fails (`dogs`.`table1`, CONSTRAINT `FK_dogs1` FOREIGN KEY (`mother_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
如何解决这个问题?我正在使用 wamp 2.0 h
和 Sqlyog
enterprise。
最佳答案
您无法直接更改由外键
值引用的主键
值。
但有多种方法可以改变它,一种方法是:
删除外键约束和主键-> 更新值(PK 和 FK)->> 然后再次添加主键和外键约束
alter table table1 drop foreign key thenameofFK;
alter table table1 drop primary key;
update table1
set id='dog4'
where id='dog1';
update table1
set mother_id='dog4'
where mother_id='dog1';
alter table table1 add primary key(id);
alter table table1
add constraint thenameofFK
foreign key(mother_id)
references table1(id);
还请从问题中删除 PHP 标签,我没有看到任何与 PHP 相关的问题或内容。
关于php - 如何解决这个约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28291015/