当前位置:网站首页>MySQL triggers
MySQL triggers
2022-07-04 14:23:00 【Fire eye Dragon】
- 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 , however , Trigger does not need to be called , When the execution in the database table DML This is triggered automatically during operation SQL Execution of fragments , No manual call required .
- stay MySQL, 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 apply the changed records in the trigger , This is similar to other databases . Now triggers only support row level triggering , Statement level triggering is not supported .
The characteristics of triggers :
- What conditions trigger :I、D、U
- When to trigger : Before or after addition, deletion and modification
- Trigger frequency : Execute... For each line
- Triggers are defined on the table , Attach to table
Basic operation
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;
for example :
-- Data preparation
CREATE DATABASE mydb10_trigger;
USE mydb10_trigger;
-- User table
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)
);
-- Need one : When user Add a row of data to the table , Will be automatically in user_log Add logging
-- Defining triggers :trigger_test1
CREATE TRIGGER trigger_test1 AFTER INSERT
ON user FOR EACH ROW
INSERT INTO user_logs VALUES (NULL,NOW(),' New users added ');
-- stay user Table add data , Let the trigger execute automatically
INSERT INTO user VALUES(1,' Zhang San ','123456');
INSERT INTO user VALUES(2,' Li Si ','234567'),(3,' Wang Wu ','345678');
-- Demand two : When user Table data is modified , Will be automatically in user_log Add logging
DELIMITER $$
CREATE TRIGGER trigger_test2 BEFORE UPDATE
ON user FOR EACH ROW
BEGIN
INSERT INTO user_logs VALUES (NULL,NOW(),' User information has been modified ');
END $$
DELIMITER ;
-- stay user Table modify data , Let the trigger execute automatically
UPDATE user SET password = '888888' WHERE uid = 1;
UPDATE user SET password = '666666' WHERE uid = 1;
NEW and OLD
Concept :MySQL It defines NEW and OLD, Used to represent the table where the trigger is located , The row that triggered the trigger , To refer to the changed record content in the trigger , Concrete :
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 Represents the data that will be or has been modified |
DELETE Type trigger | OLD Data that will be or has been deleted |
Method :NEW.columnName (columnName A column name for the corresponding data table )
-- Data preparation
CREATE DATABASE mydb10_trigger;
USE mydb10_trigger;
-- User table
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)
);
-- Need one : When user Add a row of data to the table , Will be automatically in user_log Add logging
-- Defining triggers :trigger_test1
CREATE TRIGGER trigger_test1 AFTER INSERT
ON user FOR EACH ROW
INSERT INTO user_logs VALUES (NULL,NOW(),' New users added ');
-- stay user Table add data , Let the trigger execute automatically
INSERT INTO user VALUES(1,' Zhang San ','123456');
INSERT INTO user VALUES(2,' Li Si ','234567'),(3,' Wang Wu ','345678');
-- Demand two : When user Table data is modified , Will be automatically in user_log Add logging
DELIMITER $$
CREATE TRIGGER trigger_test2 BEFORE UPDATE
ON user FOR EACH ROW
BEGIN
INSERT INTO user_logs VALUES (NULL,NOW(),' User information has been modified ');
END $$
DELIMITER ;
-- stay user Table modify data , Let the trigger execute automatically
UPDATE user SET password = '888888' WHERE uid = 1;
UPDATE user SET password = '666666' WHERE uid = 1;
-- INSERT Type of trigger
-- NEW
-- Defining triggers :trigger_test3
CREATE TRIGGER trigger_test3 AFTER INSERT
ON user FOR EACH ROW
INSERT INTO user_logs VALUES (NULL,NOW(),CONCAT(' New users added , The message is :',NEW.uid,NEW.username,NEW.password));
INSERT INTO user VALUES(4,' Zhao Liu ','234567');
-- UPDATE Type of trigger
-- OLD
CREATE TRIGGER trigger_test4 AFTER UPDATE
ON user FOR EACH ROW
INSERT INTO user_logs VALUES(NULL,NOW(),CONCAT(' User information modification , The information was modified to :',OLD.uid,OLD.username,OLD.password));
UPDATE user SET password ='9999999' WHERE uid=4;
-- NEW
CREATE TRIGGER trigger_test5 AFTER UPDATE
ON user FOR EACH ROW
INSERT INTO user_logs VALUES(NULL,NOW(),CONCAT_WS(',',' User information modification , The information is modified to :',NEW.uid,NEW.username,NEW.password));
UPDATE user SET password ='000000' WHERE uid=1;
-- DELETE Type of trigger
-- OLD
CREATE TRIGGER trigger_test6 AFTER DELETE
ON user FOR EACH ROW
INSERT INTO user_logs VALUES(NULL,NOW(),CONCAT_WS(',',' User information has been deleted , The deleted user information is :',OLD.uid,OLD.username,OLD.password));
DELETE FROM user WHERE uid=4;
Other operating
Check triggers
Method :
SHOW triggers;
Delete trigger
Method :
DROP TRIGGER [IF EXISTS] trigger_name;
for example :
-- Check triggers
SHOW TRIGGERS;
-- Delete trigger
DROP TRIGGER IF EXISTS trigger_test6;
matters needing attention
- MySQL The trigger in cannot insert,update,delete operation , To prevent recursive loops from triggering .
- Use as few triggers as possible , Suppose the trigger triggers each execution 1s,insert table 500 Data , Then you need to trigger 500 trigger , Just the time it takes for the trigger to execute 500s, and insert 500 The total number of pieces of data is 1s, that insert The efficiency of is very low .
- Triggers are for each row ; Do not use triggers on tables with frequent additions, deletions, and changes , Because it will consume resources very much .
边栏推荐
- R语言使用lattice包中的bwplot函数可视化箱图(box plot)、par.settings参数自定义主题模式
- Map of mL: Based on Boston house price regression prediction data set, an interpretable case is realized by using the map value to the LIR linear regression model
- Basic mode of service mesh
- Unity shader learning (3) try to draw a circle
- MySQL的存储过程练习题
- 【算法leetcode】面试题 04.03. 特定深度节点链表(多语言实现)
- Rich text editing: wangeditor tutorial
- R语言使用dplyr包的group_by函数和summarise函数基于分组变量计算目标变量的均值、标准差
- Error in find command: paths must precede expression (turn)
- The game goes to sea and operates globally
猜你喜欢
Test process arrangement (3)
Visual Studio调试方式详解
The failure rate is as high as 80%. What are the challenges on the way of enterprise digital transformation?
nowcoder重排链表
商業智能BI財務分析,狹義的財務分析和廣義的財務分析有何不同?
Understand chisel language thoroughly 06. Chisel Foundation (III) -- registers and counters
C# wpf 实现截屏框实时截屏功能
NowCoder 反转链表
[FAQ] Huawei Account Service Error Report 907135701 Common reasons Summary and Solutions
Excel quickly merges multiple rows of data
随机推荐
数据仓库面试问题准备
尊重他人的行为
IP lab monthly resumption · issue 5
Understand chisel language thoroughly 11. Chisel project construction, operation and test (III) -- scalatest of chisel test
Test evaluation of software testing
Fs4059c is a 5V input boost charging 12.6v1.2a. Inputting a small current to three lithium battery charging chips will not pull it dead. The temperature is 60 ° and 1000-1100ma is recommended
Rich text editing: wangeditor tutorial
How to package QT and share exe
LifeCycle
R语言ggplot2可视化:gganimate包创建动态折线图动画(gif)、使用transition_reveal函数在动画中沿给定维度逐步显示数据
Understand chisel language thoroughly 05. Chisel Foundation (II) -- combinational circuits and operators
The font of markdown grammar is marked in red
opencv3.2 和opencv2.4安装
Vscode common plug-ins summary
Why should Base64 encoding be used for image transmission
redis 日常笔记
卷积神经网络经典论文集合(深度学习分类篇)
Ws2818m is packaged in cpc8. It is a special circuit for three channel LED drive control. External IC full-color double signal 5v32 lamp programmable LED lamp with outdoor engineering
Understand chisel language thoroughly 03. Write to the developer of Verilog to chisel (you can also see it without Verilog Foundation)
10.(地图数据篇)离线地形数据处理(供Cesium使用)