当前位置:网站首页>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语言ggplot2可视化:gganimate包创建动画图(gif)、使用anim_save函数保存gif可视化动图
- MySQL之详解索引
- Detailed index of MySQL
- 数据仓库面试问题准备
- Understand chisel language thoroughly 11. Chisel project construction, operation and test (III) -- scalatest of chisel test
- Introducing testfixture into unittest framework
- 2022 practice questions and mock exams for the main principals of hazardous chemical business units
- 迅为IMX6Q开发板QT系统移植tinyplay
- 瑞吉外卖笔记
- gin集成支付宝支付
猜你喜欢

Real time data warehouse

Test process arrangement (3)

sql优化之explain

商业智能BI财务分析,狭义的财务分析和广义的财务分析有何不同?

Ruiji takeout notes

Mask wearing detection based on yolov1

Data warehouse interview question preparation

codeforce:C. Sum of Substrings【边界处理 + 贡献思维 + 灵光一现】

Map of mL: Based on Boston house price regression prediction data set, an interpretable case of xgboost model using map value

Understand chisel language thoroughly 10. Chisel project construction, operation and testing (II) -- Verilog code generation in chisel & chisel development process
随机推荐
sql优化之explain
Code hoof collection of wonderful secret place
Product identification of intelligent retail cabinet based on paddlex
Can mortgage with housing exclude compulsory execution
How to package QT and share exe
Leetcode T49: 字母异位词分组
学内核之三:使用GDB跟踪内核调用链
Install MySQL
迅为IMX6Q开发板QT系统移植tinyplay
失败率高达80%,企业数字化转型路上有哪些挑战?
C # WPF realizes the real-time screen capture function of screen capture box
Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test
What is the real meaning and purpose of doing things, and what do you really want
R语言使用dplyr包的group_by函数和summarise函数基于分组变量计算目标变量的均值、标准差
R语言ggplot2可视化:gganimate包创建动态折线图动画(gif)、使用transition_reveal函数在动画中沿给定维度逐步显示数据
Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]
Chapter 17 process memory
Redis daily notes
Understand chisel language thoroughly 09. Chisel project construction, operation and testing (I) -- build and run chisel project with SBT
瑞吉外卖笔记