当前位置:网站首页>[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 and Stock 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 one Atomic manipulation , Or all , Or none at all . In case of special circumstances , You may also need to manually maintain the data , This is very It'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 .

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 include INSERTUPDATEDELETE 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 , will Automatically 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 by BEGIN…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
 Insert picture description here

  • 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)

 Insert picture description here

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
     Insert picture description here

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 add manager_id = 103 Pay for
     Insert picture description here

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);

 Insert picture description here

  • 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);

 Insert picture description here

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

 Insert picture description here

  • The following commands are recommended to be executed under the visualization software
SHOW TRIGGERS;

 Insert picture description here

The way 2: View the definition of a trigger in the current database

SHOW CREATE TRIGGER  Trigger Name 

 Insert picture description here

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 .

 Insert picture description here

  • 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 .

 Insert picture description here

  • 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.

原网站

版权声明
本文为[Charming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061244264300.html