[英]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.