Table of Contents
Trigger overview
Creation of triggers
Code example 1
1. One of the biggest problems of triggers is poor readability.
Note that if a foreign key constraint is defined in the child table, and the foreign key specifies the ON UPDATE/DELETE CASCADE/SET NULL clause, modifying the parent table will be referenced. When the key value or the record row referenced by the parent table is deleted, it will also cause modification and deletion operations of the child table. At this time, the triggers defined based on the UPDATE and DELETE statements of the child table will not be activated.
Home Database Mysql Tutorial MySQL explains in simple terms how to use triggers

MySQL explains in simple terms how to use triggers

Sep 01, 2022 pm 02:41 PM
mysql

Recommended learning: mysql video tutorial

In actual development, we often encounter such a situation: there are 2 Or multiple interrelated tables, such as product information and inventory information are stored in two different data tables respectively. When we add a new product record, in order to ensure the integrity of the data, we must also add a new product record to the inventory table. Inventory records. In this way, we must write these two associated operation steps into the program and wrap them with transactions to ensure that these two operations become an atomic operation, either all of them are executed or none of them are executed.

If you encounter special circumstances, you may need to manually maintain the data, so it is easy to forget one step, resulting in data loss. At this time, we can use triggers. You can create a trigger so that the insertion of product information data automatically triggers the insertion of inventory data. In this way, you don’t have to worry about missing data due to forgetting to add inventory data.

Trigger overview

MySQL supports triggers starting from version 5. 0. 2. MySQL triggers, like stored procedures, are programs embedded in the MySQL server. A trigger is an operation triggered by an event, including INSERT, UPDATE, and DELETE events.

The so-called event refers to the user's action or triggering a certain behavior. If a trigger program is defined, when the database executes these statements, it is equivalent to an event occurring, and the trigger will be automatically triggered to perform the corresponding operation. When performing insert, update, and delete operations on data in a data table and need to automatically perform some database logic, triggers can be used to achieve this.

Creation of triggers

Create trigger syntax

CREATE TRIGGER 触发器名称 
{BEFORE|AFTER} {INSERT|UPDATE|DELETE} ON 表名 
FOR EACH ROW 
触发器执行的语句块;
Copy after login

Description:

Table name: Indicates the object monitored by the trigger.

BEFORE | AFTER: Indicates the trigger time. BEFORE means trigger before the event; AFTER means trigger after the event.

INSERT | UPDATE | DELETE: Indicates the triggered event.

INSERT means it is triggered when a record is inserted;

UPDATE means it is triggered when a record is updated;

DELETE means it is triggered when a record is deleted.

Code example 1

Create two tables

CREATE TABLE test_trigge r (
id INT PRIMARY KEY AUTO_INCREMENT ,
t_note VARCHAR ( 30 )
) ;
CREATE TABLE test_trigger_log (
id INT PRIMARY KEY AUTO_INCREMENT ,
t_log VARCHAR ( 30 )
) ;
Copy after login

Create a trigger

DELIMITER / /
CREATE TRIGGER befo_re_insert
BEFORE INSERT ON test_trigger 
FOR EACH ROW
BEGIN
 INSERT INTO test_trigger_log ( t_log )
 VALUES ( ' befo re_inse rt ' ) ;
END / /
DELIMITER ;
Copy after login

Insert data into the test_trigger data table

INSERT INTO test_trigger (t_note) VALUES ('测试 BEFORE INSERT 触发器');
Copy after login

View the data in the test_trigger_log data table

SELECT * FROM test_trigger_log
Copy after login
Copy after login

##Code example 2

Create a trigger

DELIMITER / /
CREATE TRIGGER after_insert
AFTER INSERT ON test_trigger
FOR EACH ROW
BEGIN
 INSERT INTO test_trigger_log ( t_log )
 VALUES ( ' after_insert ' ) ;
END / /
DELIMITER ;
Copy after login

Insert data into the test_trigger data table.

INSERT INTO test_trigger (t_note) VALUES ('测试 AFTER INSERT 触发器');
Copy after login

View the data in the test_trigger_log data table

SELECT * FROM test_trigger_log
Copy after login
Copy after login

Code example 3

Define the trigger "salary_check_trigger", based on the employee table" employees" INSERT event, before INSERT, check whether the salary of the new employee to be added is greater than the salary of his leader. If it is greater than the salary of the leader, an error of sqlstate_value being 'HY000' will be reported, causing the addition to fail.

DELIMITER //
CREATE TRIGGER salary_check_trigger
BEFORE INSERT ON employees FOR EACH ROW
BEGIN
DECLARE mgrsalary DOUBLE;
SELECT salary INTO mgrsalary FROM employees WHERE employee_id = NEW.manager_id;
IF NEW.salary > mgrsalary THEN
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = '薪资高于领导薪资错误';
END IF;
END //
DELIMITER ;
Copy after login

The NEW keyword in the trigger declaration process above represents the new record of the INSERT statement.

View deletion triggers

Method 1: View the definition of all triggers in the current database

SHOW TRIGGERS
Copy after login

Method 2: View the definition of a trigger in the current database

SHOW CREATE TRIGGER 触发器名
Copy after login

Method 3: Query the "salary_check_trigger" trigger information from the TRIGGERS table of the system library information_schema.

SELECT * FROM information_schema.TRIGGERS;
Copy after login

Delete trigger

DROP TRIGGER IF EXISTS 触发器名称
Copy after login
Advantages of triggers

1. Triggers can ensure data integrity.

Suppose we use the purchase order header table (demo.importhead) to save the overall information of the purchase order, including the purchase order number, supplier number, warehouse number, total purchase quantity, total purchase amount and acceptance date.

Use the purchase order details table (demo.importdetails) to save the details of the purchased goods, including the purchase order number, product number, and purchase quantity

The quantity, purchase price and purchase amount are not equal to the total quantity and total amount in the purchase order details. This is a data inconsistency.

In order to solve this problem, we can use triggers to stipulate that whenever there is data insertion, modification and deletion in the purchase order detail table

, the 2-step operation will be automatically triggered:

1) Recalculate the total quantity and total amount in the purchase order detail table;

2) Use the values ​​calculated in the first step to update the total quantity and total amount in the purchase order header table.

In this way, the total quantity and total amount in the purchase order header table will always be the same as the total quantity and

calculated in the purchase order detail table. The data is consistent and does not conflict with each other.

2. Triggers can help us record operation logs.

Using triggers, you can specifically record what happened at what time. For example, recording the trigger for modifying the member's stored value amount is a very good example. This is very helpful for us to restore the specific scenario when the operation is performed and better locate the cause of the problem.

3. Triggers can also be used to check the validity of data before operating it.

For example, when a supermarket purchases goods, the warehouse manager needs to enter the purchase price. However, it is easy to make mistakes in human operations. For example, when entering the quantity

, you scan the barcode; when entering the amount, you read the serial number, and the entered price far exceeds the selling price, resulting in a loss on the books. Huge losses...

These can all be used through triggers to check the corresponding data before the actual insertion or update operation, prompt errors in time, and prevent

wrong data enter the system.

Disadvantages of triggers

1. One of the biggest problems of triggers is poor readability.

Because triggers are stored in the database and driven by events, this means that triggers may not be controlled by the application layer. This is very challenging for system maintenance.

For example, create a trigger to modify member recharge operations. If there is a problem with the operation in the trigger, the update of the member's stored value amount will fail. I use the following code to demonstrate

The result shows that the system prompts an error and the field "aa" does not exist.

This is because the data insertion operation in the trigger has one more field, and the system prompts an error. However, if you don't understand this trigger, you may think that there is a problem with the update statement itself, or there is a problem with the structure of the member information table. Maybe you will also add a field called "aa" to the member information table to try to solve this problem, but the result will be in vain.

2. Changes in related data may cause trigger errors.

Especially changes in the data table structure may cause trigger errors, thus affecting the normal operation of data operations. These will affect the efficiency of troubleshooting the cause of errors in the application due to the concealment of the trigger itself.

Notes

Note that if a foreign key constraint is defined in the child table, and the foreign key specifies the ON UPDATE/DELETE CASCADE/SET NULL clause, modifying the parent table will be referenced. When the key value or the record row referenced by the parent table is deleted, it will also cause modification and deletion operations of the child table. At this time, the triggers defined based on the UPDATE and DELETE statements of the child table will not be activated.

For example: The DELETE statement based on the child table employee table (t_employee) defines trigger t1, and the department number (did) field of the child table defines a foreign key constraint that refers to the parent table department table (t_department). The primary key column is the department number (did), and the foreign key has the "ONDELETE SET NULL" clause added. Then if the parent table department table (t_department) is deleted at this time, the child table employee table (t_employee)

Recommended learning :

mysql video tutorial

The above is the detailed content of MySQL explains in simple terms how to use triggers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles