MySQL 外键约束和触发器,级联删除

こ雲淡風輕ζ 提交于 2019-12-10 03:14:07

-- 创建测试主表. ID 是主键.
CREATE TABLE test_main (
  id      INT   NOT NULL,
  value   VARCHAR(10),
  PRIMARY KEY(id)  
);
  
-- 创建测试子表. 
CREATE TABLE test_sub (
  id      INT  NOT NULL,
  main_id INT ,
  value   VARCHAR(10),
  PRIMARY KEY(id)  
); 
 
-- 插入测试主表数据.
INSERT INTO test_main(id, value) VALUES (1, 'ONE');
INSERT INTO test_main(id, value) VALUES (2, 'TWO');
 
-- 插入测试子表数据.
INSERT INTO test_sub(id, main_id, value) VALUES (1, 1, 'ONEONE');
INSERT INTO test_sub(id, main_id, value) VALUES (2, 2, 'TWOTWO');


通过  DELETE CASCADE  外键约束的处理机制来处理
mysql> ALTER TABLE test_sub
    ->   ADD CONSTRAINT main_id_cons
    ->   FOREIGN KEY (main_id)
    ->   REFERENCES  test_main(id)
    ->   ON DELETE CASCADE//
Query OK, 2 rows affected (0.16 sec)
Records: 2  Duplicates: 0  Warnings: 0
 
mysql> DELETE FROM
    ->   test_main
    -> WHERE
    ->   id = 1;
    -> //
Query OK, 1 row affected (0.02 sec)
 
mysql> SELECT
    ->   *
    -> FROM
    ->   test_sub;
    -> //
+----+---------+--------+
| id | main_id | value  |
+----+---------+--------+
|  2 |       2 | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)

如果你非要使用触发器来处理, 那么下面是一个例子:

-- 创建测试主表. ID 是主键.
CREATE TABLE t_test_main (
  id      INT   NOT NULL,
  value   VARCHAR(10),
  PRIMARY KEY(id)  
);
  
-- 创建测试子表. 
CREATE TABLE t_test_sub (
  id      INT  NOT NULL,
  main_id INT ,
  value   VARCHAR(10),
  PRIMARY KEY(id)  
);
  
-- 插入测试主表数据.
INSERT INTO t_test_main(id, value) VALUES (1, 'ONE');
INSERT INTO t_test_main(id, value) VALUES (2, 'TWO');
 
-- 插入测试子表数据.
INSERT INTO t_test_sub(id, main_id, value) VALUES (1, 1, 'ONEONE');
INSERT INTO t_test_sub(id, main_id, value) VALUES (2, 2, 'TWOTWO');
  
 
DELIMITER //
 
CREATE TRIGGER tr_t_test_main_Del
  BEFORE DELETE ON t_test_main
FOR EACH ROW
BEGIN
  DELETE FROM t_test_sub WHERE main_id = OLD.id;
END;
//
 
DELIMITER ;
 
  
mysql> delete from  t_test_main  where id = 1;
Query OK, 1 row affected (0.01 sec)
 
mysql> select * from t_test_sub;
+----+---------+--------+
| id | main_id | value  |
+----+---------+--------+
|  2 |       2 | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)
 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!