当其密钥被删除时,有一个条目自动删除mysql

时间:2015-08-15 19:26:48

标签: mysql

我有一个带有id列的用户表

一个配置文件表,其中包含一个id列和一个user_id col,它引用了用户表中的id

我想删除用户时自动删除个人资料。

这可以在mysql中使用吗?

2 个答案:

答案 0 :(得分:2)

您可以在表定义中执行此ON DELETE CASCADE命令。

请参阅:MySQL foreign key constraints, cascade delete

或者你可以使用触发器来做同样的事情:

CREATE
TRIGGER  `delete_from_profile`
AFTER DELETE ON `user`
FOR EACH ROW
BEGIN    
    DELETE 
    FROM profile
    WHERE user_id = old.id; 
END

答案 1 :(得分:2)

假设PARENT和CHILD实体之间存在1到N的关系,因此当您删除PARENT时,将根据需要删除关联的CHILD。为此,您可以使用下面的ON DELETE CASCADE

您需要注意的是,根据您的设计,如果CHILD实体与一个或多个实体相关联,那么您可能会导致意外问题,例如破坏关系,删除关联表中的记录等。另请阅读上面的链接中的存储引擎,您不能使用MuISAM

<强> PARENT

CREATE TABLE `parent` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

儿童

CREATE TABLE `child` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `parent_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  KEY `FK_1_idx` (`parent_id`),
  CONSTRAINT `FK_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

示例

填充父级

mysql> INSERT INTO parent (name) VALUES ('parent_1'), ('parent_2');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM parent;
+----+----------+
| id | name     |
+----+----------+
|  1 | parent_1 |
|  2 | parent_2 |
+----+----------+
2 rows in set (0.00 sec)

填充儿童

mysql> INSERT INTO child (name, parent_id) VALUES ('child_1', 1), ('child_2', 1), ('child_3', 2);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0
mysql> SELECT * FROM child;
+----+---------+-----------+
| id | name    | parent_id |
+----+---------+-----------+
|  1 | child_1 |         1 |
|  2 | child_2 |         1 |
|  3 | child_3 |         2 |
+----+---------+-----------+
3 rows in set (0.00 sec)

删除

mysql> DELETE FROM parent WHERE name = 'parent_1';
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM child;
+----+---------+-----------+
| id | name    | parent_id |
+----+---------+-----------+
|  3 | child_3 |         2 |
+----+---------+-----------+
1 row in set (0.00 sec)