search
HomeDatabaseMysql TutorialMySQL trigger usage
MySQL trigger usageDec 12, 2016 am 11:53 AM
mysql trigger

MySQL includes support for triggers. A trigger is a database object related to table operations. When a specified event occurs on the table where the trigger is located, the object will be called, that is, the operation event of the table triggers the execution of the trigger on the table.

Create a trigger
In MySQL, the syntax for creating a trigger is as follows:

CREATE TRIGGER trigger_name
trigger_time
trigger_event ON tbl_name
FOR EACH ROW
trigger_stmt

Among them:

trigger_name: identifies the trigger name, specified by the user;
trigger_time: identifies the triggering time, the value is BEFORE or AFTER;
trigger_event: identifies the trigger event, the value is INSERT, UPDATE or DELETE;
tbl_name: identifies the table name to create the trigger, that is, on which table the trigger is created;
trigger_stmt: trigger program body, which can be a SQL statement, or use BEGIN and END contain multiple statements.

It can be seen that 6 types of triggers can be created, namely: BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE, AFTER INSERT, AFTER UPDATE, AFTER DELETE.

Another limitation is that you cannot create 2 triggers of the same type on a table at the same time, so a maximum of 6 triggers can be created on a table.

trigger_event detailed explanation
MySQL except for INSERT, UPDATE, DELETE In addition to defining basic operations, it also defines LOAD DATA and REPLACE statements, which can also cause the triggering of the above 6 types of triggers.

The LOAD DATA statement is used to load a file into a data table, which is equivalent to a series of INSERT operations.

The REPLACE statement is generally very similar to the INSERT statement, except that when there is a primary key or unique index in the table, if the inserted data is different from the original When the primary key or unique index is consistent, the original data will be deleted first, and then a new piece of data will be added. In other words, a REPLACE statement is sometimes equivalent to one.

INSERT statement is sometimes equivalent to a DELETE statement plus an INSERT statement.

INSERT type trigger: The trigger is activated when a row is inserted, and may be triggered by INSERT, LOAD DATA, REPLACE statements;
UPDATE Type trigger: The trigger is activated when a certain row is changed, which may be triggered by the UPDATE statement;
DELETE type trigger: The trigger is activated when a certain row is deleted, which may be triggered by Triggered by DELETE and REPLACE statements.

BEGIN … END Detailed explanation
In MySQL, the syntax of the BEGIN … END statement is:

BEGIN
[statement_list]
END
Among them, statement_list Represents a list of one or more statements. Each statement in the list must be terminated with a semicolon (;).
In MySQL, the semicolon is the identifier of the end of the statement. Encountering a semicolon means that the statement has ended and MySQL can start execution. Therefore, the interpreter encounters statement_list Execution starts after the semicolon in , and then an error is reported because no END matching BEGIN is found.

The DELIMITER command will be used at this time (DELIMITER is the delimiter, which means separator). It is a command and does not require an end-of-statement identifier. The syntax is:
DELIMITER new_delemiter
new_delemiter It can be set to 1 or more length symbols. The default is semicolon (;). We can change it to other symbols, such as $:
DELIMITER $
The statement after this ends with a semicolon, and the interpreter will not react. Only when $ is encountered, the statement is considered to have ended. Note that after using it, we should remember to modify it back.

A complete example of creating a trigger
Suppose there are two tables in the system:
Class table class(class number classID, number of students in the class stuCount)
Student table student (student ID, classID)
To create a trigger to automatically update the number of students in the class table as students are added, the code is as follows:

DELIMITER $
create trigger tri_stuInsert after insert
on student for each row
begin
declare c int;
set c = (select stuCount from class where classID=new.classID);
update class set stuCount = c + 1 where classID = new.classID;
end$
DELIMITER ;

Detailed explanation of variables
Use DECLARE in MySQL to define a Local variable, this variable can only be used in BEGIN ... END It is used in compound statements and should be defined at the beginning of compound statements,

that is, before other statements. The syntax is as follows:

DECLARE var_name[,...] type [DEFAULT value]
where:
var_name is the variable name, the same as SQL The statements are the same, variable names are not case-sensitive; type is any data type supported by MySQL; multiple variables of the same type can be defined at the same time, separated by commas; the initial value of the variable is NULL, if necessary, you can use The DEFAULT clause provides a default value, which can be specified as an expression.

Use SET statement for variable assignment, the syntax is:

SET var_name = expr [,var_name = expr] ...

NEW and OLD detailed explanation

The NEW keyword is used in the above example, and in MS SQL Server INSERTED and DELETED are similar. NEW and DELETED are defined in MySQL. OLD, used to represent

In the table where the trigger is located, the row of data that triggered the trigger.
Specifically:
In INSERT type triggers, NEW Used to represent new data that will be (BEFORE) or has been (AFTER) inserted;
In UPDATE type triggers, OLD is used to represent the original data that will be or has been modified, NEW Used to represent new data that will be or has been modified;
In DELETE type triggers, OLD is used to represent the original data that will be or has been deleted;
Usage: NEW.columnName (columnName is a column name of the corresponding data table)
In addition, OLD is read-only, while NEW can use SET in triggers Assign a value so that the trigger will not be triggered again and cause a circular call (for example, before inserting a student, add "2013" before its student number).

Viewing triggers

is the same as viewing databases (show databases;) and viewing tables (show tables;). The syntax of viewing triggers is as follows:

SHOW TRIGGERS [FROM schema_name];
where, schema_name is the name of the Schema, In MySQL Schema and Database are the same, that is to say, you can specify the database name, so you don't have to "USE database_name;" first.

Delete triggers


Same as deleting databases and tables, the syntax of deleting triggers is as follows:

DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name

The execution order of triggers


The database we created It is generally an InnoDB database, and the tables created on it are transactional tables, that is, transaction safe. At this time, if the SQL statement or trigger fails to execute, MySQL The transaction will be rolled back, including:

① If the BEFORE trigger fails to execute, SQL cannot be executed correctly.

②When SQL execution fails, the AFTER trigger will not fire.

③AFTER If a trigger of type fails to execute, SQL will roll back.

Do you guys have some understanding of the use of mysql triggers? If you have any questions, please leave me a message and we can make progress together.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you alter a table in MySQL using the ALTER TABLE statement?How do you alter a table in MySQL using the ALTER TABLE statement?Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

How do I configure SSL/TLS encryption for MySQL connections?How do I configure SSL/TLS encryption for MySQL connections?Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

How do you handle large datasets in MySQL?How do you handle large datasets in MySQL?Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you drop a table in MySQL using the DROP TABLE statement?How do you drop a table in MySQL using the DROP TABLE statement?Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

How do you represent relationships using foreign keys?How do you represent relationships using foreign keys?Mar 19, 2025 pm 03:48 PM

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

How do you create indexes on JSON columns?How do you create indexes on JSON columns?Mar 21, 2025 pm 12:13 PM

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?Mar 18, 2025 pm 12:00 PM

Article discusses securing MySQL against SQL injection and brute-force attacks using prepared statements, input validation, and strong password policies.(159 characters)

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft