繁体   English   中英

为什么不能放下外键?

[英]Why can't I drop a foreign key?

场景:

Parent table | id primary key, message_p
Child  table | id primary key, parent_id foreign key, message_c

我在父表中有1行数据,在子表中有2行数据。 我想测试FK关系强制执行的约束。 然后,我尝试从子表中删除外键,以便即使子表有2行,我也可以继续删除父行:

alter table child 
drop foreign key parent_id

然后出现以下错误:

[1091-无法删除'parent_id'; 检查列/键是否存在]

笔记:

show create table child

CREATE TABLE `track` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `member_id` int(11) NOT NULL,
 `title` varchar(50) DEFAULT NULL,
 `artist` varchar(50) DEFAULT 'TBA',
 `album` varchar(50) DEFAULT 'TBA',
 `genre` varchar(50) DEFAULT 'TBA',
 `dance_style` varchar(50) DEFAULT 'TBA',
 PRIMARY KEY (`id`),
 KEY `member_id` (`member_id`),
 CONSTRAINT `track_ibfk_1` FOREIGN KEY (`member_id`) REFERENCES `member` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

我在查询中是否缺少某些内容或对FK的一般了解?

您试图按列名删除外键约束,这就是为什么您的代码无法正常工作的原因。

首先查询您的外键约束名称(使用show create table child就像显示键名称一样,类似于track_ibfk_1

如果您尝试了注释中的所有内容(假设表名称正确,约束名称正确……),我认为没有理由不起作用。

但是,如果您还有其他持有父(或“成员”)外键的表,也许这些约束阻止了父条目的删除?

无论如何,下面的示例显示了删除外键实际上是可行的:

drop table if exists  testchild;
drop table if exists  test;

create table test(
id int primary key,
name varchar(50)
);

create table testchild(
childid int primary key,
reftotest int,
constraint reftotest_FK foreign key (reftotest) references test(id)
);

insert into test values (1, 'Jack'),  (2, 'Sam');
insert into testchild values (1, 1), (2, 2), (3, 1);

insert into testchild values (4,5); # will fail
delete from test where id = 1; # will fail

alter table testchild drop foreign key reftotest_FK;
insert into testchild values (4,5); # will not fail any more
delete from test where id = 1; # will not fail any more

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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