[英]MYSQL Unable to update parent table - Relational Database Design, foreign key constraints and cascading update / delete
I have a very simple database design for managing TV shows: 我有一个非常简单的数据库设计来管理电视节目:
tv_shows
. 父表: tv_shows
。 Primary key: show_id
主键: show_id
seasons
. 子表: seasons
。 Primary key: season_id
, Foreign key: show_id
主键: season_id
,外键: show_id
episodes
. 子表: episodes
。 Primary key: episode_id
, Foreign key: season_id
主键: episode_id
,外键: season_id
Table creation SQL: 表创建SQL:
$sql = "DROP TABLE IF EXISTS ".$table_shows.";
CREATE TABLE $table_shows (
show_id int(11) NOT NULL,
name varchar(120) DEFAULT NULL,
PRIMARY KEY (show_id),
UNIQUE KEY show_id_UNIQUE (show_id)
) $charset_collate;
DROP TABLE IF EXISTS ".$table_seasons.";
CREATE TABLE $table_seasons (
season_id int(10) NOT NULL,
show_id int(11) DEFAULT NULL,
name varchar(120) DEFAULT NULL,
PRIMARY KEY (season_id),
KEY seasons_ibfk_1 (show_id),
CONSTRAINT seasons_ibfk_1 FOREIGN KEY (show_id) REFERENCES $table_shows (show_id) ON DELETE CASCADE ON UPDATE CASCADE
) $charset_collate;
DROP TABLE IF EXISTS ".$table_episodes.";
CREATE TABLE $table_episodes (
episode_id int(10) NOT NULL,
season_id int(10) DEFAULT NULL,
name varchar(120) DEFAULT NULL,
PRIMARY KEY (episode_id),
KEY season_id (season_id),
CONSTRAINT episodes_ibfk_1 FOREIGN KEY (season_id) REFERENCES $table_seasons (season_id)
) $charset_collate;";
What I want to happen is if a show was deleted from the tv_shows
table, then the delete cascades, so the seasons
and episodes
are also deleted from their respective tables. 我想发生的事情是,如果从tv_shows
表中删除了某个节目,则删除级联,因此seasons
和episodes
也从其各自的表中删除。
I can insert into these tables fine. 我可以插入这些表中。 But if I try and delete a row from the tv_shows table then I get an SQL error: 但是,如果我尝试从tv_shows表中删除一行,则会收到SQL错误:
ERROR 1451: 1451: Cannot delete or update a parent row: a foreign key constraint fails
So where have I gone wrong with my FK constraints? 那么我的FK约束哪里出错了?
You need to add the ON DELETE CASCADE
to the episodes as well. 您还需要在片段中添加ON DELETE CASCADE
。 This ensures that they all follow each other into the bin. 这样可以确保它们彼此跟随进入垃圾箱。
CONSTRAINT episodes_ibfk_1
FOREIGN KEY (season_id)
REFERENCES $table_seasons (season_id)
ON DELETE CASCADE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.