当前位置:网站首页>Mysql8.0 learning record 20 - trigger
Mysql8.0 learning record 20 - trigger
2022-07-24 19:22:00 【wisfy_ twenty-one】
What is trigger ?
Triggers are associated with specific tables , And the named database object triggered according to the specific event of the table .
Its creation syntax is as follows :
CREATE
[DEFINER = user]
TRIGGER [IF NOT EXISTS] trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
[trigger_order]
trigger_body
trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }
trigger_order: { FOLLOWS | PRECEDES } other_trigger_name
The same schema The name of the trigger in must be unique .
From the definition syntax of trigger, we can see , The corresponding three types of events triggered :INSERT、UPDATE、DELETE. This is not just for insert/update/delete sentence :
- INSERT: When a new row is added , image INSERT\LOAD DATA\REPLACE Statements can trigger
- UPDATE: When a row of data is modified , Generally speaking, it means update sentence
- DELETE: When a row of data is deleted , It's usually delete or replace sentence . Be careful DROP TABLE or TRUNCATE TABLE It doesn't trigger delete event .
Each of the above events has two trigger opportunities :BEFORE and AFTER . In triggers , Can pass OLD and NEW Refers to the value before modification and the new value ,insert Events cannot be used OLD,delete Events cannot be used NEW.OLD The value of is read-only and cannot be modified , But it can go through set modify NEW Value . It should be noted that , Only BEFORE To modify the insert or update New value of .AFTER no way , Because the data modification has been completed .
There's another thing to pay attention to here ,NEW and OLD Cannot reference generated column .
If multiple triggers with the same event and the same timing are defined on the same table , So by default , Create first, execute first . If there is order dependency , So you can go through FOLLOWS and PRECEDES Indicates that it is executed after or before other triggers .
Example 1 of trigger : Count the total number of large tables
Encountered a particularly large table , Every time the total number of statistics will be particularly stressful . In this case, triggers can be used to count :
create table t_count(
id int primary key auto_increment,
name varchar (10),
num int
);
create table t_count_sum(
total long
);
insert into t_count_sum values(0);
-- Every new row of data , Counting plus one
create trigger t_record_sum_plus after insert on t_count
for each row
update t_count_sum set total = total+1;
-- Every row of data deleted , Count minus one
create trigger t_record_sum_subtract after delete on t_count
for each row
update t_count_sum set total = total-1;
Test it :
insert into t_count(name,num) values('a',1),('b',2),('c',2);
delete from t_count where name = 'b';
select * from t_count_sum;
total|
-----+
2 |
Example 2 of trigger : Count the total number of new data in a reply and the average value of a field
Still used t_count This table , Refer to the example on the official website :
delimiter //
create trigger t_num_avg after insert on t_count
for each row
begin
set @sum = @sum + NEW.num;
set @total = @total+1;
set @avg = @sum/@total;
end
//
delimiter ;
test :
set @sum = 0;
set @total = 0;
insert into t_count(name,num) values('a',1),('b',2),('c',3),('d',4);
select @avg;
insert into t_count(name,num) values('e',4);
select @avg;
@avg |
-----------+
2.500000000|
@avg |
-----------+
2.800000000|
Conditions related to the failure of the trigger
- If one BEFORE Trigger failed , Then the operation of the response line will not be executed
- BEFORE Triggers are used when an operation attempts to add or modify data , It will be carried out , It doesn't matter whether the corresponding operation is successful
- AFTER Triggers are only relevant BEFORE And response line operations are successful before execution
- BEFORE and AFTER Failure of trigger itself , It will cause the statement that triggers the trigger to execute to fail
Other matters needing attention
- Triggers cannot use statements that explicitly or implicitly start or end a transaction , for example START TRANSACTION, COMMIT, or ROLLBACK.
- Stored procedures can be used in triggers to reuse the same code , But the corresponding stored procedure should not return data or use dynamic SQL
Function of trigger
- Can be used to implement InnoDB The statistics in the following table
- It can be used to verify and correct data
- It can be used to track users' operations on the database
- You can perform cascading updates of tables
- It can be used to replicate table data
- Data values can be calculated automatically , If the value of the data meets certain requirements , Then specific processing is carried out .
边栏推荐
- How does PostgreSQL decide PG's backup strategy
- Literature reading: gopose 3D human pose estimation using WiFi
- Hucang integrated release of full data value, sequoiadb V5.2 online conference heavy attack
- MySQL hidden version number
- First knowledge database
- asp. Net core, C # summary about path
- Oneinstack installation and configuration PHP 8.1 and MySQL 8.0-oneinstack site building novice tutorial
- Convolutional Neural Networks in TensorFlow quizs on Coursera
- Introduction to VIM
- Techempower web framework performance test 21st round results release --asp Net core continue to move forward
猜你喜欢

In the spring of domestic databases

【JVM学习03】类加载与字节码技术
![[laser principle and application -6]:q switching element and Q drive circuit board](/img/30/e199b73fb9b0ad335f26f2378cfc45.png)
[laser principle and application -6]:q switching element and Q drive circuit board
思源笔记 v2.1.2 同步问题

Techempower web framework performance test 21st round results release --asp Net core continue to move forward

Leetcode652 finding duplicate subtrees

Day 9 (this keyword and experiment)
Siyuan notes V2.1.2 synchronization problem

day 1

文献阅读:GoPose 3D Human Pose Estimation Using WiFi
随机推荐
asp. Net coree file upload and download example
MySQL version 5.7.9 SQL_ mode=only_ full_ group_ By question
Decision tree_ ID3_ C4.5_ CART
Channel state information (CSI) conjugate multiplication denoising method
JVM method call
Clion configuring WSL tool chain
Process pool and fallback function [easy to understand]
Analysis of the basic concept of digital warehouse
OpenGL learning (III) glut two-dimensional image rendering
[untitled]
PCIe link initialization & Training
OpenGL learning (V) modern OpenGL triangle rendering
Math
Taokeeper environment setup
Machine learning_ Softmax function (multi classification problem)
FPGA 20 routines: 9. DDR3 memory particle initialization write and read through RS232 (Part 2)
Sqoop
Ensure the health and safety of front-line construction personnel, and implement wrong time construction at Shenzhen construction site
[JVM learning 04] JMM memory model
Detailed explanation of the relationship between MySQL tables