当存在外键约束时,更改主键的值(特定记录的ID)

时间:2013-08-21 14:48:28

标签: mysql foreign-keys

以下是我正在尝试做的基本要点:

create table main(id char(1) primary key);

create table other (
  id int primary key auto_increment,
  main_id char(1),
  key m (main_id),
  constraint fk foreign key (main_id) references main(id)
);

insert into main(id) values('a');
insert into other(main_id) values('a');

update main inner join other on other.main_id=main.id
set main.id='b', other.main_id='b'
where main.id='a';

这会导致外键约束失败。有没有办法在不删除外键的情况下完成此操作(在我的大型生产数据库中不是一个真正的选项)?

1 个答案:

答案 0 :(得分:2)

您只需在会话中临时设置foreign_key_checks=0即可完成此操作:

set foreign_key_checks=0;

update main inner join other on other.main_id=main.id
set main.id='b', other.main_id='b'
where main.id='a';

另一个选项是使用ON UPDATE CASCADE选项配置外键,这样如果在父表上更新主键,它将级联到子表:

create table main(id char(1) primary key);

create table other (
  id int primary key auto_increment,
  main_id char(1),
  key m (main_id),
  constraint fk foreign key (main_id) references main(id) on update cascade
);