MySQL 外鍵約束和觸發器,級聯刪除

-- 建立測試主表. 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');mysql


經過  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)sql

若是你非要使用觸發器來處理, 那麼下面是一個例子:測試

-- 建立測試主表. 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)
 test

相關文章
相關標籤/搜索