Home >Database >Mysql Tutorial >How to use MySql database triggers

How to use MySql database triggers

WBOY
WBOYforward
2023-05-27 10:02:072759browse

    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:yisu.com. If there is any infringement, please contact admin@php.cn delete