简体   繁体   中英

I can't edit table that another table has a foreign key of it in mysql

This is my SQL code in MySQL:

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
);


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
);

Create table Table1_sal
(
  salid varchar(2),
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

Table1 and Table1_Addr are two tables that Table1_sal has two foreign keys to these two tables.

My problem is that I can't change id field of Table1 and addid field of Table1_Addr

The error is:

#1451 - Cannot delete or update a parent row: a foreign key constraint
fails (`avl`.`table1_sal`, CONSTRAINT `table1_sal_ibfk_2` FOREIGN KEY (`id`)
REFERENCES `table1` (`id`))


Edited-The answer is:

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
);


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
);

Create table Table1_sal
(
  salid varchar(2),
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid)ON UPDATE CASCADE ON DELETE CASCADE,
  FOREIGN KEY (id) REFERENCES Table1(id)ON UPDATE CASCADE ON DELETE CASCADE
)

Add ON UPATE CASCADE after your foreign keys definitions

    FOREIGN KEY (addid) REFERENCES Table1_Addr(addid) ON UPDATE CASCADE ON DELETE CASCADE,
  FOREIGN KEY (id) REFERENCES Table1(id) ON UPDATE CASCADE ON DELETE CASCADE

You have to set the foreign key to On Update cascade.Then all child rows will also be updated

     Create table Table1_sal
(
  salid varchar(2),
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid) 
   On delete cascade On Update cascade ,
  FOREIGN KEY (id) REFERENCES Table1(id) 
   On delete cascade On Update cascade
)

您无法更改Table1和Table1_Addr的主键(即Table1_Addr的外键)的问题是关系数据库的正常行为,例如MySQL,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM