search
HomeDatabaseMysql TutorialHow 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.

    How to use MySql database triggers

    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;

    How to use MySql database triggers

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    MySQL String Types: Storage, Performance, and Best PracticesMySQL String Types: Storage, Performance, and Best PracticesMay 10, 2025 am 12:02 AM

    MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

    Understanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreUnderstanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreMay 10, 2025 am 12:02 AM

    MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

    What are the String Data Types in MySQL?What are the String Data Types in MySQL?May 10, 2025 am 12:01 AM

    MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

    How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

    TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

    How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

    ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

    MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

    ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

    MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

    The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

    MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

    The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

    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

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment