这是我在MySQL中的SQL代码:
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和Table1_Addr是两个表,Table1_sal有两个外键到这两个表。
我的问题是我无法更改Table1的id字段和Table1_Addr的addid字段
错误是:
#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`))
编辑 - 答案是:
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
)
答案 0 :(得分:1)
在外键定义
之后添加ON UPATE CASCADE
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
答案 1 :(得分:1)
您必须将外键设置为On Update cascade。然后所有子行也将更新
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
)
答案 2 :(得分:0)
您无法更改Table1和Table1_Addr的主键(Table1_Addr的外键)的问题是关系数据库的正常行为,如MySQL,