[英]Foreign Key Constraint On delete cascade not effective
I have created two tables (emp and dept). 我创建了两个表(emp和dept)。 Emp contains a foreign key (deptid).
Emp包含一个外键(肽)。 I am attempting to delete a row from the dept table and am receiving a foreign key constraint error.
我试图从dept表中删除一行,并收到一个外键约束错误。 I then altered the emp table foreign key to add constraint and delete on cascade.
然后,我更改了emp表外键以添加约束并在级联上删除。 The code is copied here
代码复制到这里
create table dept (
deptid int primary key,
deptname varchar(20),
locid int);
create table emp (
empid int primary key,
frname varchar(15),
lname varchar(20),
hiredate datetime,
deptid int,
foreign key (deptid) references dept(deptid));
alter table emp add constraint fk_deptid foreign key (deptid)
references dept(deptid) on delete cascade;
This is the error message that I receive: 这是我收到的错误消息:
Query Error: Error: ER_ROW_IS_REFERENCED_2: Cannot delete or update a parent row: a foreign key constraint fails (
test
.emp
, CONSTRAINTemp_ibfk_1
FOREIGN KEY (deptid
) REFERENCESdept
(deptid
))查询错误:错误:ER_ROW_IS_REFERENCED_2:不能删除或更新父行,外键约束失败(
test
。emp
,约束emp_ibfk_1
外键(deptid
)参考dept
(deptid
))
The problem is that you are creating two foreign key constraints for the same column. 问题是您要为同一列创建两个外键约束。 Avoid doing this, it's confusing.
避免这样做,这很令人困惑。
The first one is created while you create the table and is unnamed . 第一个在创建表时创建,并且未命名 。 Since you didn't provide a name for it, MySQL automatically names it for you as
emp_ibfk_1
. 由于您没有提供名称,因此MySQL会自动为您命名为
emp_ibfk_1
。 This one does not have CASCADE DELETE
and prevents deletion of parent keys. 这个没有
CASCADE DELETE
,可以防止删除父键。
The second one is on a separate SQL statement and you name it fk_deptid
. 第二个是在单独的SQL语句上,您将其命名为
fk_deptid
。 This one has CASCADE DELETE
and allows deletion of parent keys. 这具有
CASCADE DELETE
并允许删除父键。
While enforcing the foreign key constraints MySQL cannot delete the row since the first constraint does not allow it. 在执行外键约束时,MySQL不能删除该行,因为第一个约束不允许该行。 That's the error you are getting.
那就是你得到的错误。
This is a confusing situation and I would avoid doing something like this. 这是一个令人困惑的情况,我会避免这样做。 I would suggest having a single FK constraint for the column;
我建议对列使用单个FK约束; specifically I would remove the first one.
具体来说,我将删除第一个。
For example: 例如:
create table dept (
deptid int primary key,
deptname varchar(20),
locid int);
create table emp (
empid int primary key,
frname varchar(15),
lname varchar(20),
hiredate datetime,
deptid int
-- , foreign key (deptid) references dept(deptid) -- removed
);
alter table emp add constraint fk_deptid foreign key (deptid)
references dept(deptid) on delete cascade;
insert into dept (deptid, deptname, locid)
values (1, 'Math', 123);
insert into emp (empid, frname, lname, hiredate, deptid)
values (10, 'Peter', 'Fonda', null, 1);
delete from dept where deptid = 1; -- works!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.