1. 程式人生 > >MySQL外鍵約束On Delete、On Update

MySQL外鍵約束On Delete、On Update

eve delet spa ted sql nes charset del blog

使用外鍵實現
Create
Table: CREATE TABLE `child` ( `par_id` int(11) NOT NULL, `child_id` int(11) NOT NULL, PRIMARY KEY (`par_id`,`child_id`), FOREIGN KEY (`par_id`) REFERENCES `parent` (`par_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8
Create Table: CREATE TABLE `parent` ( `par_id` int(11) NOT NULL, PRIMARY KEY (`par_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
使用mysql trigger實現
mysql> show triggers\G$ *************************** 1. row *************************** Trigger: t12 Event: UPDATE Table
: t3 Statement: begin update t4 set tid = new.id where tid = old.id; end Timing: AFTER Created: NULL sql_mode: NO_ENGINE_SUBSTITUTION Definer: root@localhost character_set_client: gbk collation_connection: gbk_chinese_ci
Database Collation: utf8_general_ci *************************** 2. row *************************** Trigger: t11 Event: DELETE Table: t3 Statement: begin update t4 set tid = 0 where tid = old.id; end Timing: AFTER Created: NULL sql_mode: NO_ENGINE_SUBSTITUTION Definer: root@localhost character_set_client: gbk collation_connection: gbk_chinese_ci Database Collation: utf8_general_ci 2 rows in set (0.02 sec)

MySQL外鍵約束On Delete、On Update