在多对多关系中删除正确

时间:2014-03-05 15:45:27

标签: mysql sql

我有一个多对多关系的简短问题。 这是我的表格:

+---------+----------------+
| film_id | title          | 
+---------+----------------+
|       1 | Apocalypse Now |
+---------+----------------+


+-------------+----------------------+
| category_id | name                 | 
+-------------+----------------------+
|           1 | cool category        |
+-------------+----------------------+
|           2 | not so cool category |
+-------------+----------------------+

+---------+-------------+
| film_id | category_id |
+---------+-------------+
|       1 |           1 |
+---------+-------------+
|       1 |           2 |
+---------+-------------+

正如您所看到的film - category - film_category - 表格中有FK。

我想要的内容:如果要删除category,则应删除film_category中出现category_id的所有条目。但不是相关的film!除此之外:这应该在删除film时起作用,反之亦然! (这正是我的问题)

我的问题:我是否可以仅使用FK定义解决问题,还是必须在删除film_category之前手动删除film - 表中的所有条目还是category

1 个答案:

答案 0 :(得分:1)

您的表格应如下所示。电影表中的删除应该删除电影类别具有相同ID的行,反之亦然,删除电影表。

CREATE TABLE `film` (
  `film_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`film_id`)
) ENGINE=InnoDB;

CREATE TABLE `category` (
  `category_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB;

CREATE TABLE `film_category` (
 `film_category_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `film_id` int(10) unsigned NOT NULL DEFAULT '0',
 `category_id` int(10) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`film_category_id`),
 KEY `film_id` (`film_id`),
 KEY `category_id` (`category_id`),
 CONSTRAINT `film_category_ibfk_2` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`) ON DELETE CASCADE,
 CONSTRAINT `film_category_ibfk_1` FOREIGN KEY (`film_id`) REFERENCES `film` (`film_id`) ON DELETE CASCADE
) ENGINE=InnoDB;

您还应该能够将以下内容用于film_category:

CREATE TABLE `film_category` (
  `film_id` int(10) unsigned NOT NULL DEFAULT '0',
  `category_id` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`film_id`,`category_id`),
  CONSTRAINT `film_category_ibfk_1` FOREIGN KEY (`film_id`) REFERENCES `film` (`film_id`) ON DELETE CASCADE,
  CONSTRAINT `film_category_ibfk_2` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`) ON DELETE CASCADE
) ENGINE=InnoDB;