MySQL Trigger Example (two table sync additions and deletions)

Source: Internet
Author: User
Tags one table mysql trigger example

The following two examples are from:
Http://www.cnblogs.com/nicholas_f/archive/2009/09/22/1572050.html
The actual measurement is valid, but the original post delimiter is not correct, so modify it slightly.
Where old means tab2 (passive trigger), new represents TAB1 (active, external application executes INSERT statement in this table)

Example 1:
Create two tables to add one record in one table, and another to add a record:
DROP TABLE IF EXISTS tab1;
CREATE TABLE Tab1 (
tab1_id varchar (11)
);

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
Delimiter | |
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| |
delimiter;

Test:
INSERT into TAB1 (tab1_id) VALUES (' 0001 ');

View results:
SELECT * from TAB1;
SELECT * from TAB2;

Example 2:
Create two tables to delete one record in one table, and another to delete a record:
Delimiter | |
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:
DELETE from Tab1 WHERE tab1_id= ' 0001 ';

Look at the results
SELECT * from TAB1;
SELECT * from TAB2;

MySQL Trigger Example (two table sync additions and deletions)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.