Use and understanding of MySQL triggers

Use and understanding of MySQL triggers

1. What is a trigger?

A special type of database program that can monitor certain data operations (insert/update/delete) and trigger related operations (insert/update/delete) to protect the integrity of the data.

My personal understanding is that it is a bit similar to Java's observer pattern. When an object changes, the observer also responds.

Mysql seems to support triggers from 5.0 onwards.

2. Create a trigger

I will introduce two ways to create triggers: creating with statements and creating with navicat.

The syntax for creating a trigger is as follows:

CREATE TRIGGER trigger_name trigger_time trigger_event ON tb_name FOR EACH ROW trigger_stmt
trigger_name: the name of the trigger trigger_time: the trigger time, which can be BEFORE or AFTER
trigger_event: trigger event, INSERT, DELETE or UPDATE
tb_name: indicates the table on which the trigger is created. trigger_stmt: the body of the trigger, which can be a SQL statement or multiple statements enclosed by BEGIN and END. So we can say that MySQL creates the following six types of triggers:
BEFORE INSERT, BEFORE DELETE, BEFORE UPDATE
AFTER INSERT,AFTER DELETE,AFTER UPDATE

The trigger name parameter refers to the name of the trigger to be created.

The BEFORE and AFTER parameters specify when the trigger is executed, before or after the event.

FOR EACH ROW means that any operation on a record that meets the trigger event will trigger the trigger.

Create multiple triggers that execute statements:

CREATE TRIGGER trigger name BEFORE | AFTER trigger event ON table name FOR EACH ROW
BEGIN
 Execute statement list END

Use of NEW and OLD:

Trigger Type Use of new and old
insert New represents newly added data
update new represents the updated data, and old represents the data before the update
delete old represents the data to be deleted

A field can be named new/lod.

Next we create two tables for testing:

stu table: main table (observed)

DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'Name',
`age` int(11) NULL DEFAULT NULL COMMENT 'Age',
`sort` int(11) NULL DEFAULT NULL COMMENT 'sort field',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 18 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

stu_log table: trigger association table (observer)

DROP TABLE IF EXISTS `stu_log`;
CREATE TABLE `stu_log` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

Now let's assume that there is a business where when data is added or deleted from the stu table, a log is synchronously recorded in stu_log, recording the name and time.

If we don't use triggers, we need to write code to implement this requirement, but triggers can help us achieve it easily.

First we create an insert trigger using the statement:

DROP TRIGGER IF EXISTS `insert_log`;
delimiter;;
CREATE TRIGGER `add_log` AFTER INSERT ON `stu` FOR EACH ROW BEGIN
INSERT INTO stu_log(name,create_time) VALUES(new.`name`,now());
END
;;
delimiter ;

Execution Result:

Then we use navicat to create a delete trigger:

Step 1: Right-click the stu table and select Design Table ---- Trigger

Step 2: Fill in the options as shown in the figure and select Trigger before deletion

Step 3: Write the execution statement in the definition box below, as shown in the figure. Remember to click Save!

Statement:

begin
INSERT INTO stu_log(name,create_time) VALUES(old.`name`,now());
end

3. Use triggers

Test it: add a new piece of data

insert into stu (name,age) VALUES('李白',36)

View the stu table and stu_log table:

As shown in the figure, the trigger has taken effect!

Test deleting a piece of data

DELETE from stu where name = 'Li Bai'

View the stu table and stu_log table:

As shown in the figure, the trigger has taken effect!

The above is the detailed content of using and understanding MySQL triggers. For more information about MySQL triggers, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of MySQL database triggers
  • MySQL trigger syntax and application examples
  • MySQL trigger principle and usage example analysis
  • Introduction to the use and advantages and disadvantages of MySQL triggers

<<:  Pure CSS to modify the browser scrollbar style example

>>:  Detailed analysis of Vue child components and parent components

Recommend

Simple steps to configure Nginx reverse proxy with SSL

Preface A reverse proxy is a server that receives...

Detailed explanation of concat related functions in MySQL

1. concat() function Function: Concatenate multip...

mysql creates root users and ordinary users and modify and delete functions

Method 1: Use the SET PASSWORD command mysql -u r...

SVG+CSS3 to achieve a dynamic wave effect

A vector wave <svg viewBox="0 0 560 20&qu...

Vue.js implements the nine-grid image display module

I used Vue.js to make a nine-grid image display m...

How to create https using nginx and Tencent Cloud free certificate

I have been studying how to get https. Recently I...

Introduction to local components in Vue

In Vue, we can define (register) local components...

Introduction to vim plugin installation under Linux system

Table of contents Install vim plugin manager Add ...

Install Kafka in Linux

Table of contents 1.1 Java environment as a prere...

Detailed explanation of the minimum width value of inline-block in CSS

Preface Recently, I have been taking some time in...

How to delete special character file names or directories in Linux

Delete a file by its inode number First use ls -i...

Detailed steps to install Docker mongoDB 4.2.1 and collect springboot logs

1: Install mongodb in docker Step 1: Install mong...

HTML tag marquee realizes various scrolling effects (without JS control)

The automatic scrolling effect of the page can be...

JavaScript to implement the web version of the snake game

This article shares the specific code for JavaScr...