为什么我不能放弃外键?(Why can't I drop a foreign key?)

编程入门 行业动态 更新时间:2024-10-23 05:37:16
为什么我不能放弃外键?(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 - 不能DROP'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的一般理解?

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. I wanted to test constraints that an FK relationship enforces. 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:

alter table child drop foreign key parent_id

I then got the following error:

[1091 - Can't DROP '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?

最满意答案

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

首先查询您的外键约束名称(使用show create table child因为您显示了键名,类似track_ibfk_1

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

更多推荐

本文发布于:2023-08-07 19:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:drop   foreign   key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!