Example ~ ~
example1:
Create a table Tab1
1234 |
DROP TABLE IF EXISTS tab1; CREATE TABLE tab1( tab1_id varchar (11) ); |
Create a table TaB2
1234 |
DROP TABLE IF EXISTS tab2; CREATE TABLE tab2( tab2_id varchar (11) ); |
Create trigger:t_afterinsert_on_tab1
Function: Automatically adds records to the TAB2 table after adding TAB1 table records
1234567 |
DROP TRIGGER IF EXISTS t_afterinsert_on_tab1; CREATE TRIGGER t_afterinsert_on_tab1 AFTER INSERT ON tab1 FOR EACH ROW BEGIN insert into tab2(tab2_id) values (new.tab1_id); END ; |
Test it.
1 |
INSERT INTO tab1(tab1_id) values ( ‘0001‘ ); |
Look at the results
12 |
SELECT * FROM tab1; SELECT * FROM tab2; |
example2:
Create trigger:t_afterdelete_on_tab1
Function: Delete the TAB1 table records automatically deleted the corresponding records in the TAB2 table
1234567 |
DROP TRIGGER IF EXISTS t_afterdelete_on_tab1; CREATE TRIGGER t_afterdelete_on_tab1 AFTER DELETE ON tab1 FOR EACH ROW BEGIN delete from tab2 where tab2_id=old.tab1_id; END ; |
Test it.
1 |
DELETE FROM tab1 WHERE tab1_id= ‘0001‘ ; |
MySQL Trigger trigger usage one (simple)