当前位置:网站首页>[MySQL] detailed explanation of trigger content of database advanced
[MySQL] detailed explanation of trigger content of database advanced
2022-07-07 08:47:00 【Xiaohuang Xiaohuang is no longer confused】
Personal home page : Huang Xiaohuang's blog home page
️ Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luckThis article is from the column :MySQL8.0 Learning notes
This article refers to the video :MySQL Database complete tutorial
Welcome to the support subscription column ️
List of articles
1 Trigger Overview
Trigger introduction :
- trigger , Is a special stored procedure . A trigger, like a stored procedure, is a function that can perform a specific function , Stored on the database server SQL fragment . But the trigger does not need to call , When executing DML This will be triggered automatically during operation SQL Execution of fragments , No manual call required .
- stay MySQL in , Only execute insert、delete、update The execution of the trigger can only be triggered when the operation ;
- This feature of trigger can help to ensure the integrity of data in database , logging , Data verification and other operations ;
- Use the alias OLD And NEW To reference the record content where the trigger changes , This is similar to other databases . Now the trigger is still Only row level triggering is supported , Statement level triggering is not supported .
Schematic diagram of trigger :
Triggers are defined on the table , Attach to table .
Triggers are defined , You need to specify the :
- What conditions trigger ? Insert 、 Delete 、 to update ?
- When to trigger ? Before or after addition, deletion and modification ?
- Trigger frequency , For each line .
2 The basic operation of trigger
2.1 Create trigger
1. Create a trigger with only one execution statement :
create trigger Trigger Name before|after Triggering event
on Table name for each row
Execute statement ;
2. Create a trigger with multiple execution statements :
create trigger Trigger Name before|after Triggering event
on Table name for each row
begin
Execute statement list
end;
2.2 Trigger operation instance
First, prepare the data , Define two tables user And user_logs, Record the user registration information and user operation log respectively . Hope to be user When something changes ,user_logs Change automatically ( It is realized by trigger ). The relevant codes for data preparation are as follows :
CREATE DATABASE IF NOT EXISTS mydatabase_tigger;
USE mydatabase_tigger;
-- User table creation
CREATE TABLE user(
uid INT PRIMARY KEY ,
username VARCHAR(50) NOT NULL ,
password VARCHAR(50) NOT NULL
);
-- User information operation log table
CREATE TABLE user_logs(
id INT PRIMARY KEY AUTO_INCREMENT,
time TIMESTAMP,
log_text VARCHAR(255)
);
- If you want to give user When adding information to the table ,user_logs The table automatically adds a row of data , A trigger is defined in the following code trigger_test01 To meet the needs , The relevant codes and results are as follows :
CREATE TRIGGER trigger_test01
AFTER INSERT
ON user
FOR EACH ROW
INSERT INTO user_logs
VALUES (NULL, NOW(), ' New users add ');
INSERT INTO user VALUES (1, 'nezuko', '123456');


- When user When the table data is modified , Automatically in user_logs Add logging ., A trigger is defined in the following code trigger_test02 To meet the needs , The relevant codes and results are as follows :
DELIMITER $$
CREATE TRIGGER trigger_test02
BEFORE UPDATE
ON user
FOR EACH ROW
BEGIN
INSERT INTO user_logs VALUES (NULL, NOW(), ' User information is modified ');
END $$
DELIMITER ;
UPDATE user SET password = '111111' WHERE uid = 1;


You can see user The password in the table has been changed , The record of modification information is successfully added to the log table .
3 NEW And OLD
3.1 Why NEW And OLD?
MySQL It defines NEW and OLD, Used to indicate that the trigger is in the table , Which row of data triggered the trigger , To refer to the changed record content in the trigger , See the following table for details :
| Trigger Type | Trigger Type NEW And OLD Use |
|---|---|
| INSERT Type trigger | NEW Indicates the data to be added or added |
| UPDATE Type trigger | OLD Represents the data before modification ,NEW Indicates the data to be or have been modified |
| DELETE Type trigger | OLD Data that will be or has been deleted |
Usage method :
NEW.columnName(columnName A column name representing the corresponding data )
What kind of requirements will be used NEW and OLD Well ?
In the case illustrated above , We modify user The password in the table , to user_logs Modification information is added to the table . But it only prompts the modified information , There is no indication that . If , It is necessary to indicate the password before modification or the password after modification in the information , You need to use the OLD and NEW Used for triggers to reference data !
3.2 NEW And OLD example
Defining triggers trigger_test03, You can give user_logs Insert modification information , Show the user's password before and after modification . The relevant codes and results are as follows :
DELIMITER $$
CREATE TRIGGER trigger_test03
BEFORE UPDATE
ON user
FOR EACH ROW
BEGIN
INSERT INTO user_logs VALUES (NULL, NOW(), CONCAT(' User information is modified , The password before modification is ', OLD.password, ', Modified for ', NEW.password));
END $$
DELIMITER ;
UPDATE user SET password = '99999999' WHERE uid = 1;


If you want to delete the trigger , You can use the following statement : Delete the three triggers created so far .
DROP TRIGGER IF EXISTS trigger_test01;
DROP TRIGGER IF EXISTS trigger_test02;
DROP TRIGGER IF EXISTS trigger_test03;
4 Other operations of trigger
- Check triggers :
show triggers;
- Delete trigger :
drop trigger if exists trigger_name;
5 Precautions for trigger
- MySQL This table cannot be insert、update、delete operation , To prevent recursive loops from triggering ;
- Use as few triggers as possible , Suppose the trigger triggers each execution 1s, Then modify the table every time 、 The update operation will take some extra time , Thus, the efficiency of table operation is low ;
- Triggers are for each row , Try not to use triggers for tables that are frequently added, deleted, or modified , Avoid additional consumption of resources ;
- Frequent use of triggers will lead to more trouble in maintaining data in the future , Because there are many behaviors in one change .
At the end
The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !
Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
边栏推荐
- You should use Google related products with caution
- Opencv learning note 5 - gradient calculation / edge detection
- Redis summary
- 指针进阶,字符串函数
- Introduction to data fragmentation
- IP地址的类别
- National standard gb28181 protocol video platform easygbs adds streaming timeout configuration
- 快速集成认证服务-HarmonyOS平台
- Gson转换实体类为json时报declares multiple JSON fields named
- Novice entry SCM must understand those things
猜你喜欢

Download and install orcale database11.2.0.4
![[南京大学]-[软件分析]课程学习笔记(一)-introduction](/img/57/bf652b36389d2bf95388d2eb4772a1.png)
[南京大学]-[软件分析]课程学习笔记(一)-introduction

Three series of BOM elements
![[Yu Yue education] basic reference materials of electrical and electronic technology of Nanjing Institute of information technology](/img/2a/01db1b84c26502c851786aaca56abe.jpg)
[Yu Yue education] basic reference materials of electrical and electronic technology of Nanjing Institute of information technology

Through the "last mile" of legal services for the masses, fangzheng Puhua labor and personnel law self-service consulting service platform has been frequently "praised"

ncs成都新电面试经验

The field value in Splunk subquery fuzzy matching CSV is*

Greenplum6.x常用语句

leetcode134. gas station

How to realize the high temperature alarm of the machine room in the moving ring monitoring system
随机推荐
PLSQL的安装和配置
Implementation of navigation bar at the bottom of applet
leetcode135. Distribute candy
Find the original code, inverse code and complement of signed numbers [C language]
Leetcode 1984. Minimum difference in student scores
求有符号数的原码、反码和补码【C语言】
調用華為遊戲多媒體服務的創建引擎接口返回錯誤碼1002,錯誤信息:the params is error
Redis summary
leetcode134. gas station
How to add a mask of a target in a picture
What are the advantages of commas in conditional statements- What is the advantage of commas in a conditional statement?
All about PDF crack, a complete solution to meet all your PDF needs
Go write a program that runs within a certain period of time
Required String parameter ‘XXX‘ is not present
[南京大学]-[软件分析]课程学习笔记(一)-introduction
Count sort (diagram)
Greenplum6.x搭建_环境配置
【踩坑】nacos注册一直连接localhost:8848,no available server
MySQL introduction - crud Foundation (establishment of the prototype of the idea of adding, deleting, changing and searching)
Sign and authenticate API interface or H5 interface
