How to use MySql database triggers
1. Introduction
1. Trigger is a special stored procedure. A trigger, like a stored procedure, is a SQL fragment that can complete a specific function and is stored on the database server. However, the trigger is silently called. When a DML operation is performed on the data in the database table, the execution of this SQL fragment is automatically triggered without manual operation. transfer.
2. In MySql, the execution of triggers can only be triggered when insert, delete, and update operations are executed.
3. This feature of triggers can help applications ensure data security on the database side. Integrity, logging, data verification and other operations
4. Use the aliases OLD and NEW to refer to the changed record content in the trigger. This is similar to other databases. Now the trigger only supports rows. Level triggering, statement level triggering is not supported
2. Operation
1. Table data preparation
# 用户表 SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键', `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '用户名', `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '性别', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; # 用户操作日志表 SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user_log -- ---------------------------- DROP TABLE IF EXISTS `user_log`; CREATE TABLE `user_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, `create_time` datetime(0) DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
2. Trigger format
# 创建只有一个执行语句的触发器 create trigger 触发器名 before|after 触发事件 on 表名 for each row 执行语句; # 创建有多个执行语句的触发器 create trigger 触发器名 before|after 触发事件 on 表名 for each row begin 执行语句列表 end;
3. Operation
drop TRIGGER if EXISTS TRIGGER_test; -- 需求1:当users表添加一行数据,则会自动在user_log添加日志记录 delimiter $$ CREATE TRIGGER TRIGGER_test after INSERT on users FOR EACH ROW BEGIN INSERT INTO user_log(content,create_time) VALUES('添加了一条数据',NOW()); end $$ delimiter ; INSERT INTO users(user_name,sex) VALUES('xiaohemaio','男'); -- 需求2:当users表修改一行数据,则会自动在user_log添加日志记录 drop TRIGGER if EXISTS TRIGGER_test1; delimiter $$ CREATE TRIGGER TRIGGER_test1 BEFORE UPDATE on users FOR EACH ROW BEGIN INSERT INTO user_log(content,create_time) VALUES('修改了一条数据',NOW()); end $$ delimiter ; update users set user_name='迪丽热巴' WHERE id=3;
3. The use of triggers NEW and OLD
NEW and OLD are defined in MySql, which are used to represent the row of data that triggered the trigger in the table where the trigger is located. References the content of the record that changed in the trigger.
Usage: NEW.columnName (columnName is the name of a column in the corresponding data table)
1. Case
-- 案例一 drop TRIGGER if EXISTS TRIGGER_test2; delimiter $$ CREATE TRIGGER TRIGGER_test2 after INSERT on users FOR EACH ROW BEGIN INSERT INTO user_log(content,create_time) VALUES(CONCAT('添加的用户信息为:',NEW.user_name,' 性别为:',NEW.sex ),NOW()); end $$ delimiter ; INSERT INTO users(user_name,sex) VALUES('xiaohemaio','男'); -- 案例二 drop TRIGGER if EXISTS TRIGGER_test3; delimiter $$ CREATE TRIGGER TRIGGER_test3 BEFORE UPDATE on users FOR EACH ROW BEGIN INSERT INTO user_log(content,create_time) VALUES(CONCAT('将:',OLD.user_name,' 修改为:',NEW.user_name ),NOW()); end $$ delimiter ; update users set user_name='迪丽热巴' WHERE id=4; -- 案例三 drop TRIGGER if EXISTS TRIGGER_test4; delimiter $$ CREATE TRIGGER TRIGGER_test4 BEFORE DELETE on users FOR EACH ROW BEGIN INSERT INTO user_log(content,create_time) VALUES(CONCAT('将id为:',OLD.user_name,' 已删除' ),NOW()); end $$ delimiter ; DELETE FROM users WHERE id=4;
4. Other operations
-- 查看触发器 SHOW TRIGGERS; -- 删除触发器 drop TRIGGER if EXISTS 触发器名;
5. Notes
1. Insert, update, and delete operations cannot be performed on this table in triggers to avoid recursive loop triggers
2. Use triggers as little as possible. Assume that the trigger is executed for 1 second each time and insert table 500 data. Then the trigger needs to be triggered 500 times. The execution time of the trigger alone takes 500s, and insert 500 A total of one piece of data takes 1 second, so the efficiency of this insert is very low.
3. Triggers are for each row of data. Remember not to use triggers on tables that are frequently added, deleted, or modified, because they consume a lot of resources.
Supplement: Verification trigger
Insert data into the user table users.
mysql> INSERT INTO users (userName, password, name, nickName, sex, email, isManager) VALUE ('itbilu', 'e10adc3949ba59abbe56e057f20f883e', 'IT笔录', 'itbilu', 1, 'cn.liuht@gmail.com', 0);
users originally had no data, and the userId of the data just inserted was 1. Insert data into the user table role table userRoles to trigger the trigger:
mysql> INSERT INTO userRoles (userId, roleId) VALUE (1, 1);
The data just inserted has triggered the trigger. The results are as follows:
mysql> select isManager from users; +-----------+ | isManager | +-----------+ | 1 | +-----------+
The above is the detailed content of How to use MySql database triggers. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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 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.

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.

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.

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.

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

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.
