2016-12-16 103 views
0

场景:为什么我不能删除外键?

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

我在父表中数据的第1行和2行子表中的数据。我想测试FK关系执行的约束条件。然后我试图从子表中删除外键,以便evene虽然子表中有2行,然后我可以继续和删除父行:

alter table child 
drop foreign key parent_id 

然后我得到了以下错误:

[1091 - Can't DROP 'parent_id'; check that column/key exists]

注:

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的一般理解的东西吗?

+0

貌似你试图通过列名来删除一个外键,而不是由外键的名称。 –

+0

另外你的'show create table child'向我们展示'track'表,确定你粘贴了正确的代码? –

+0

但请注意,在该表上,约束名称是'track_ibfk_1'。你的'child'表应该会发生同样的情况,所以你试图按列名删除外键,而不是外键名。 –

回答

0

您试图通过列名称删除外键约束,这就是为什么您的代码不起作用。

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

0

如果你尝试了一切,评论(假设正确的表名,约束名,...),我看不出有什么理由不应该工作。

如果你有,但是,持外键父(或“成员”)其他表,也许这些约束堵父项的?

不管怎么说,这里是一个示例,显示删除外键实体LLY工作:

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 
相关问题