Example ~ ~
example1:
Create a table Tab1
| 1234 |
DROPTABLE IF EXISTS tab1;CREATE TABLEtab1( tab1_id varchar(11)); |
Create a table TaB2
| 1234 |
DROPTABLE IF EXISTS tab2;CREATE TABLEtab2( tab2_id varchar(11)); |
Create trigger:t_afterinsert_on_tab1
Function: Automatically adds records to the TAB2 table after adding TAB1 table records
| 1234567 |
DROPTRIGGER IF EXISTS t_afterinsert_on_tab1;CREATE TRIGGER t_afterinsert_on_tab1 AFTER INSERT ON tab1FOR EACH ROWBEGIN insert intotab2(tab2_id) values(new.tab1_id);END; |
Test it.
| 1 |
INSERTINTOtab1(tab1_id) values(‘0001‘); |
Look at the results
| 12 |
SELECT* FROM tab1;SELECT * FROMtab2; |
example2:
Create trigger:t_afterdelete_on_tab1
Function: Delete the TAB1 table records automatically deleted the corresponding records in the TAB2 table
| 1234567 |
DROPTRIGGER IF EXISTS t_afterdelete_on_tab1;CREATE TRIGGER t_afterdelete_on_tab1AFTER DELETE ON tab1FOR EACH ROWBEGIN delete from tab2 wheretab2_id=old.tab1_id;END; |
Test it.
| 1 |
DELETEFROM tab1 WHEREtab1_id=‘0001‘; |
MySQL Trigger trigger usage one (simple)