Example:
Existing tables tab1 and tab2
The trigger must have the following functions
When you insert a record to tab1, tab2 also inserts the same record.
Mysql> delimiter // mysql> Create trigger t_afterinsert_on_tab1-> after insert on tab1-> for each row-> begin-> insert into tab2 (tab2_id) values (New. tab1_id);-> end;-> //
Execute the following statement to restore the settings.
Mysql> delimiter;
The role of Delimiter is to tell the MySQL interpreter whether the command has been completed and whether MySQL can be executed.By default, Delimiter is a semicolon ;. In the command line client, if a command line ends with a semicolon,After you press enter, MySQL will execute this command. But sometimes, you don't want MySQL to do this.The statement contains a semicolon. Use delimiter //,In this way, the MySQL interpreter will execute this statement only when // appears.You can also create a trigger using batch processing.
Create trigger t_afterinsert_on_tab1after insert on tab1for each rowbegin insert into tab2 (tab2_id) values (New. tab1_id); end;
Save the preceding content as an SQL FileRun it. Note that Delimiter is also used to change the statement end mark.Delete trigger:
Drop trigger t_afterinsert_on_tab1;
Why do I use for each row when creating a trigger? This is because when this sentence is added, the trigger event is Row-level. Therefore, an event must be triggered for each row.