当前位置:网站首页>[MySQL] trigger
[MySQL] trigger
2022-07-06 20:57:00 【Charming】
In actual development , We often encounter such situations : Yes 2 One or more interrelated tables , Such as
Commodity information
andStock information
Store separately 2 In two different data tables , When we add a new product record , In order to ensure the integrity of the data , An inventory record must be added to the inventory table at the same time .
thus , We must write these two associated operation steps into the program , And use it
Business
Wrap it up , Make sure these two operations become oneAtomic manipulation
, Or all , Or none at all . In case of special circumstances , You may also need to manually maintain the data , This is veryIt's easy to forget one step
, Leading to data loss .
This is the time , You can use triggers . You can create a trigger , Let the insertion of commodity information data automatically trigger the insertion of inventory data . thus , Don't worry about missing data caused by forgetting to add inventory data .
List of articles
1. Trigger Overview
MySQL from
5.0.2
Trigger is supported in version .MySQL The trigger is the same as the stored procedure , Are embedded in MySQL A program of the server .The trigger is made by
Events to trigger
Some operation , These events includeINSERT
、UPDATE
、DELETE
event . The so-called event refers to the user's action or triggering a certain behavior . If the trigger program is defined , When the database executes these statements , It's equivalent to an event , willAutomatically
The trigger performs the corresponding action .When inserting data in the data table 、 Update and delete operations , When some database logic needs to be executed automatically , Triggers can be used to implement .
2. Trigger creation
2.1 Create trigger Syntax
- The syntax for creating triggers is :
CREATE TRIGGER Trigger Name
{BEFORE|AFTER} {
INSERT|UPDATE|DELETE} ON Table name
FOR EACH ROW
The block of statements executed by the trigger ;
explain :
Table name
: Represents the object monitored by the trigger .BEFORE|AFTER
: Indicates the trigger time .BEFORE Indicates that... Is triggered before the event ;AFTER Indicates that... Is triggered after the event .INSERT|UPDATE|DELETE
: Indicates the event triggered .- INSERT Indicates that... Is triggered when a record is inserted ;
- UPDATE Indicates that... Is triggered when the record is updated ;
- DELETE Indicates that... Is triggered when a record is deleted .
The block of statements executed by the trigger
: It can be a single SQL sentence , It can also be done byBEGIN…END
Structure .
2.2 The code for
give an example 1:
1、 Create data table :
CREATE TABLE test_trigger (
id INT PRIMARY KEY AUTO_INCREMENT,
t_note VARCHAR(30)
);
CREATE TABLE test_trigger_log (
id INT PRIMARY KEY AUTO_INCREMENT,
t_log VARCHAR(30)
);
2、 Create trigger : Create name as before_insert
The trigger of , towards test_trigger
Data table before inserting data , towards test_trigger_log
Insert... Into the data table before_insert
Log information .
DELIMITER //
CREATE TRIGGER before_insert
BEFORE INSERT ON test_trigger
FOR EACH ROW
BEGIN
INSERT INTO test_trigger_log (t_log)
VALUES('before_insert');
END //
DELIMITER ;
3、 towards test_trigger
Insert data into the data table
INSERT INTO test_trigger (t_note) VALUES (' test BEFORE INSERT trigger ');
4、 see test_trigger
Table data
- see
test_trigger_log
Data in the data table
mysql> SELECT * FROM test_trigger_log;
+----+---------------+
| id | t_log |
+----+---------------+
| 1 | before_insert |
+----+---------------+
1 row in set (0.00 sec)
give an example 2:
1、 Create name as after_insert
The trigger of , towards test_trigger
After inserting data into the data table , towards test_trigger_log
Insert... Into the data table after_insert
Log information .
- Be careful : as follows
$
It can also represent the terminator
DELIMITER $
CREATE TRIGGER after_insert
AFTER INSERT ON test_trigger
FOR EACH ROW
BEGIN
INSERT INTO test_trigger_log (t_log)
VALUES('after_insert');
END $
DELIMITER ;
2、 towards test_trigger
Insert data into the data table .
INSERT INTO test_trigger (t_note) VALUES (' test AFTER INSERT trigger ');
3、 see test_trigger_log
Data in the data table
mysql> SELECT * FROM test_trigger_log;
+----+---------------+
| id | t_log |
+----+---------------+
| 1 | before_insert |
| 2 | before_insert |
| 3 | after_insert |
+----+---------------+
3 rows in set (0.00 sec)
- Here are two records , The reason is that befor_insert and after_insert Two triggers , So when inserting a piece of data , It will trigger twice
give an example 3: Defining triggers “salary_check_trigger
”, Based on employee table “employees
” Of INSERT
event , stay INSERT
Check whether the salary of the new employee to be added is greater than that of his leader , If it is greater than the leader's salary , Then newspaper sqlstate_value
by ’HY000
’ Error of , This makes the addition fail .
DELIMITER //
CREATE TRIGGER salary_check_trigger
BEFORE INSERT ON employees FOR EACH ROW
BEGIN
DECLARE mgrsalary DOUBLE;
# Query to add data manager Pay for
SELECT salary INTO mgrsalary FROM employees WHERE employee_id = NEW.manager_id;
IF NEW.salary > mgrsalary THEN
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = ' The salary is higher than the leader's salary ';
END IF;
END //
DELIMITER ;
In the above trigger declaration process NEW
Keyword represents INSERT
Add a new record of the statement .
test :
Add success : Still triggered the trigger
salary_check_trigger
Implementation
View what you want to addmanager_id = 103
Pay for
INSERT INTO employees(employee_id,last_name,email,hire_date,job_id,salary,manager_id)
VALUES(300,'Tom','[email protected]',CURDATE(),'AD_VP',8000,103);
- Add failure , At this time, the salary of the added data exceeds manager_id = 103 Pay for
9000
INSERT INTO employees(employee_id,last_name,email,hire_date,job_id,salary,manager_id)
VALUES(301,'Jerry','[email protected]',CURDATE(),'AD_VP',10000,103);
3. see 、 Delete trigger
3.1 Check triggers
- View trigger is to view the definition of triggers that already exist in the database 、 Status and syntax information .
The way 1: View the definitions of all triggers in the current database G
Similar to the semicolon at the end ”;
“, It is recommended to execute this command at the command line
SHOW TRIGGERS\G
- The following commands are recommended to be executed under the visualization software
SHOW TRIGGERS;
The way 2: View the definition of a trigger in the current database
SHOW CREATE TRIGGER Trigger Name
The way 3: From the system library information_schema
Of TRIGGERS
Query in table “salary_check_trigger
” Trigger information .
SELECT * FROM information_schema.TRIGGERS;
3.2 Delete trigger
Triggers are also database objects , Delete triggers also use DROP
sentence , The syntax is as follows :
DROP TRIGGER IF EXISTS Trigger Name ;
4. Advantages and disadvantages of flip flops
4.1 advantage
1、 Triggers ensure data integrity .
- Hypothetical use
Purchase order header table
(demo.importhead) To save the overall information of the purchase order , Include purchase order number 、 Vendor No 、 Warehouse number 、 Total incoming quantity 、 Total purchase amount and acceptance date .
- use
Purchase order details
(demo.importdetails) To save the details of incoming goods , Include purchase order number 、 Product id 、 Purchase quantity 、 Purchase price and purchase amount .
Whenever you enter 、 When deleting and modifying a purchase order detail data , The data in the purchase order details will change . This is the time , The total quantity and total amount in the purchase order header table must be recalculated , otherwise , The total quantity and total amount in the purchase order header table are not equal to the total quantity and total amount in the purchase order details , This is data inconsistency .
To solve this problem , You can use triggers , It is stipulated that whenever there is data insertion in the purchase order details 、 When modifying and deleting , Automatic triggering 2 Step by step :
1) Recalculate the total quantity and total amount in the purchase order details ;
2) Update the total quantity and total amount in the purchase order header table with the value calculated in step 1 .
- thus , The value of total quantity and total amount in the purchase order header table , It is always the same as the total quantity and total amount calculated in the purchase order details , The data is consistent , There will be no contradiction .
2、 Triggers can help record operation logs .
- Using triggers , You can record exactly when and what happened . such as , Record the trigger for modifying the member's stored value . This is for the specific scenario when we perform the restore operation , It's helpful to better locate the cause of the problem .
3、 Triggers can also be used before manipulating data , Check the validity of the data .
- such as , When the supermarket buys goods , The warehouse keeper needs to enter the purchase price . however , Human operation is easy to make mistakes , For example, when entering quantity , Scan the bar code in ; When entering the amount , Look at the string , The entered price far exceeds the selling price , Resulting in huge losses on the book …… These can be triggered , Before the actual insert or update operation , Check the corresponding data , Prompt errors in time , Prevent erroneous data from entering the system .
4.2 shortcoming
1、 One of the biggest problems with triggers is poor readability .
Because triggers are stored in the database , And driven by events , This means that triggers are possible
Not controlled by the application layer
. This is very challenging for system maintenance .such as , Create a trigger to modify the member stored value operation . If something goes wrong with the operation in the trigger , It will lead to failure in updating the member's stored value . Use the following code to demonstrate :
mysql> update demo.membermaster set memberdeposit=20 where memberid = 2;
ERROR 1054 (42S22): Unknown column 'aa' in 'field list'
Results show , The system prompts an error , Field “aa” non-existent .
This is because , The data insertion operation in the trigger has one more field , The system prompts an error . But , If you don't understand this trigger , It is likely that it is the problem of updating the statement itself , Or there is something wrong with the structure of the member information table . Maybe you'll add a name to the member information table called “aa” Field of , Try to solve this problem , The result can only be in vain .
2、 Change of relevant data , May cause trigger errors .
- Especially the change of data table structure , Can cause trigger errors , Thus affecting the normal operation of data operation . These are due to the concealment of the trigger itself , It affects the efficiency of error cause troubleshooting in the application .
4.3 Be careful
Be careful , If a foreign key constraint is defined in the child table , And the foreign key specifies ON UPDATE/DELETE CASCADE/SET NULL Clause , At this time, when modifying the key value referenced by the parent table or deleting the record row referenced by the parent table , It will also cause modification and deletion of sub tables , At this point, based on the sub table UPDATE and DELETE The trigger defined by the statement is not activated .
for example : Employee table based on sub table (t_employee) Of DELETE Statement defines the trigger t1, And the department number of the sub table (did) The field defines the foreign key constraint and references the parent table department table (t_department) The primary key column of the department number (did), And the foreign key is added “ON DELETE SET NULL” Clause , Then, if the parent table department table is deleted at this time (t_department) In the sub table employee table (t_employee) When there are department records matching records , Will cause sub table employee table (t_employee) The department number of the matching record (did) It is amended as follows NULL, However, the trigger is not activated at this time t1. Only direct sub table employee table (t_employee) perform
DELETE
Statement to activate the trigger t1.
边栏推荐
- Swagger UI教程 API 文档神器
- Comprehensive evaluation and recommendation of the most comprehensive knowledge base management tools in the whole network: flowus, baklib, jiandaoyun, ones wiki, pingcode, seed, mebox, Yifang cloud,
- 每个程序员必须掌握的常用英语词汇(建议收藏)
- Summary of different configurations of PHP Xdebug 3 and xdebug2
- 如何实现常见框架
- [200 opencv routines] 220 Mosaic the image
- 新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
- C language games - three chess
- 硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件
- 动态切换数据源
猜你喜欢
监控界的最强王者,没有之一!
Spark SQL chasing Wife Series (initial understanding)
面试官:Redis中有序集合的内部实现方式是什么?
Application layer of tcp/ip protocol cluster
使用.Net分析.Net达人挑战赛参与情况
Opencv learning example code 3.2.3 image binarization
None of the strongest kings in the monitoring industry!
##无yum源安装spug监控
15 millions d'employés sont faciles à gérer et la base de données native du cloud gaussdb rend le Bureau des RH plus efficace
Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache
随机推荐
c#使用oracle存储过程获取结果集实例
Value of APS application in food industry
OAI 5G NR+USRP B210安装搭建
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
1500萬員工輕松管理,雲原生數據庫GaussDB讓HR辦公更高效
(work record) March 11, 2020 to March 15, 2021
7. Data permission annotation
How to turn a multi digit number into a digital list
##无yum源安装spug监控
Redis insert data garbled solution
Web开发小妙招:巧用ThreadLocal规避层层传值
15 millions d'employés sont faciles à gérer et la base de données native du cloud gaussdb rend le Bureau des RH plus efficace
use. Net drives the OLED display of Jetson nano
防火墙基础之外网服务器区部署和双机热备
Huawei device command
Infrared thermometer based on STM32 single chip microcomputer (with face detection)
Spiral square PTA
I've seen many tutorials, but I still can't write a program well. How can I break it?
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀