简体   繁体   English

为什么不能放下外键?

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

Scenario: 场景:

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

I had 1 row of data in the parent table and 2 rows of data in the child table. 我在父表中有1行数据,在子表中有2行数据。 I wanted to test constraints that an FK relationship enforces. 我想测试FK关系强制执行的约束。 I then attempted to remove the foreign key from the child table so that evene though the child table had 2 rows, I could then go ahead and remove the parent row: 然后,我尝试从子表中删除外键,以便即使子表有2行,我也可以继续删除父行:

alter table child 
drop foreign key parent_id

I then got the following error: 然后出现以下错误:

[1091 - Can't DROP 'parent_id'; [1091-无法删除'parent_id'; check that column/key exists] 检查列/键是否存在]

Notes: 笔记:

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

Am I missing something in my query or the general understanding about FK's? 我在查询中是否缺少某些内容或对FK的一般了解?

You are trying to delete the Foreign Key Constraint by column name, that's why your code doesn't work. 您试图按列名删除外键约束,这就是为什么您的代码无法正常工作的原因。

First query your foreign key constraint name (using show create table child as you did show the key name, something like track_ibfk_1 首先查询您的外键约束名称(使用show create table child就像显示键名称一样,类似于track_ibfk_1

If you tried out everything as commented (assuming correct table names, constraint names, ...), I see no reason why it should not work. 如果您尝试了注释中的所有内容(假设表名称正确,约束名称正确……),我认为没有理由不起作用。

If you have, however, other tables that hold foreign keys to parent (or 'member'), maybe that these constraints block removal of parent entries? 但是,如果您还有其他持有父(或“成员”)外键的表,也许这些约束阻止了父条目的删除?

Anyway, here is an example showing that dropping a foreign key actually works: 无论如何,下面的示例显示了删除外键实际上是可行的:

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