drngnh708353 2015-02-03 03:45
浏览 78

如何解决此约束错误

I have table1 with 3 columns: id varchar(20), name, mother_id varchar(20). mother_id is a foreign key referring to the id column in the same table.

Here is my table:

|id     |name    |mother_id|  
|dog1   |my_dog  | (null)    
|dog2   |my_dog2 | dog1    
|dog3   |my_dog3 | dog1

If I tried to update dog1 and change dog4 I have this error:

 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) 

How to solve this problem? I'm using wamp 2.0 h and Sqlyog enterprise.

  • 写回答

1条回答 默认 最新

  • dongze8698 2015-02-03 04:08
    关注

    You can not directly change a Primary key value which is referenced by a Foreign key value. but there is multi ways to change it one way is:

    drop the Foreign key constraint and Primary key -> update the values (PK and FK) -> and then add the primary key and Foreign Key constraint again

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

    also please remove PHP tag from question, I don't see any issue or content related to PHP.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?