MySQL database trigger)

Source: Internet
Author: User

MySQL database trigger)

MySQL trigger: monitors a situation and triggers an operation

I. Four Elements

Trigger time: before/after

Location: table

Monitoring Operation: insert/update/delete

Trigger operation: insert/update/delete

 

Ii. Create a trigger

Delimiter $ # change the SQL terminator to $ to facilitate writing SQL statements triggered

Create trigger triggerName after/before insert/update/delete on tableName

For each row

Begin

SQL statement; # The statement to be triggered

End $

 

Test Table: item table (g), order table (o)

3. delete a monitor

Drop trigger triggerName

 

4. Order (o) and item table (g) Data trigger update

Create trigger tg after insert on o

For each row

Begin

Update g set num = num-new.much where id = new. gid;

End $

 

PS: for monitoring insert operations, new rows are represented by new

The value of each column in the row, which is retrieved using the new. Column name.

 

5. delete an order and add the item table accordingly.

Create trigger tg after delete on o

For each row

Begin

Update g set num = num + old. much where id = old. gid;

End $

 

6. Modify an order and change the item table accordingly.

Create trigger tg after update on o

For each row

Begin

Update g set num = num + old. much-new.much where id = old. gid;

End $

 

7. Differences between after and before

After is the process of adding, deleting, modifying, and triggering the data operation.

Before is triggered first to determine whether the trigger conditions are met, and then add, delete, and modify data.

This article permanently updates the link address:

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.