Deep understanding of MySQL triggers

Basic understanding:

1. Use occasion:

Triggers are based on events, and the main event is the addition, deletion, and modification of MySQL, namely insert, delete, and update.

2. Trigger naming

Trigger names exist in the schema namespace, meaning that all triggers must have unique names within a schema. Triggers in different schemas can have the same name.

Because the trigger is in the namespace of a single table, the trigger name of the same table needs to be different. Different tables can have the same trigger name.

3. Trigger execution order

If there is the same update (or delete, insert) trigger, it will be executed according to the time of creation.

And FOLLOWS and PRECEDES can modify the execution order of trigger

For example, the official case:

mysql> CREATE TRIGGER ins_transaction BEFORE INSERT ON account

      FOR EACH ROW PRECEDES ins_sum

      SET

      @deposits = @deposits + IF(NEW.amount>0,NEW.amount,0),

      @withdrawals = @withdrawals + IF(NEW.amount<0,-NEW.amount,0);

Query OK, 0 rows affected (0.01 sec)

ins_transaction and ins_sum are the names of the two triggers.

4. The role of the trigger :

1. Security. The user can have certain rights to operate the database based on the value of the database.

1) The user's operation can be restricted based on time, for example, it is not allowed to modify the database data after work and holidays.

2) The user's operation can be restricted based on the data in the database, for example, the purchase amount of a single commodity is not allowed to be greater than a fixed value.

2. Audit. Can track user operations on the database. 

 1) Audit statements of user operation database.

 2) Write user updates to the database into the audit table.

I have n’t used it since I have n’t used it. I will add it later.

3. Implement complex data integrity rules

Implement non-standard data integrity checks and constraints. Triggers can produce more complex restrictions than rules. Unlike rules, triggers can reference columns or database objects. For example, a trigger can roll back any futures that attempt to eat more than its own margin.

4. Implement complex non-standard database-related integrity rules.

1) Triggers can update serially related tables in the database. This is a more frequently used realization function.

2) The trigger can reject or roll back those changes that damage the relevant integrity and cancel the transaction that attempts to update the data. This kind of trigger works when inserting an external key that does not match its primary key.

In the following example, I will describe these two features in more detail.

5. Synchronize the data in the table in real time.

6. Automatically calculate the data value, if the data value meets certain requirements, then carry out specific processing.

For example, if the funds in the company's account are less than 50,000 yuan, then immediately send warning data to the financial staff.

( 1 ) Insert data:

When a user adds an order, we need to make corresponding changes to the storage in the commodity table

mysql> create trigger shop_goods
    -> after insert on shoppingcar
    -> for each row
    -> update goods set storage=storage-new.amount where id=new.g_id
    -> ;
Query OK, 0 rows affected (0.03 sec)

mysql>insert into shoppingcar values(1,1,2);

search result:

goods表
+-------+---------+-------------+---------+
| id    | gname   | description | storage |
+-------+---------+---------- --+---------+
|  1    |  huawei |  rongyao9   |    198  |
|  2    |  iphone |  iphoneX    |    100  |
+-------+---------+-------------+---------+

shoppingcar表
+----- -+----- -+--------+
| u_id  | g_id  | amount |
+-------+-------+--------+
|  1    |   1   |  2     |
+-------+-------+--------+

About the use of new and old

new represents a new data row, and old represents an old data row

( 2 ) Delete data

For example, when a user cancels an order, we need to add back the quantity of goods

mysql> create trigger shop_good1
    -> after delete on shoppingcar
    -> for each row
    -> update goods set storage=storage+old.amount where id=old.g_id;
Query OK, 0 rows affected (0.01 sec)
删除前:
mysql> select  * from goods;
+-----+---------+-------------+---------+
| id  | gname   | description | storage |
+-----+---------+-------------+---------+
|  1  |  huawei | rongyao9    |    198  |
|  2  |  iphone | iphoneX     |    100  |
+-----+---------+-------------+---------+
2 rows in set (0.00 sec)


mysql> select  * from shoppingcar;
+------+------+--------+
| u_id | g_id | amount |
+------+------+--------+
|   1  |   1  |     2  |
+------+------+--------+
1 rows in set (0.00 sec)
Delete data: 
mysql > delete from shoppingcar where g_id = 1 ; 
Query OK, 1 row affected (0.03 sec)

result:

( 3 ) Update data (can increase or decrease)

When the user wants to modify the quantity of a certain commodity purchased by modifying the quantity of the shopping cart, then our inventory also needs to be changed.

mysql> create trigger shop_good2
    -> after update on shoppingcar
    -> for each row
    -> update goods set storage=storage-new.amount+old.amount where id=new.g_id/old.g_id;
Query OK, 0 rows affected (0.14 sec)

View trigger commands

show triggers

This command can only see what triggers are there, but not the specific information of triggers.

All trigger information is stored in the triggers table under the information_schema database, and can be queried using SELECT statements. If there are many triggers, it is best to query a certain trigger through the TRIGGER_NAME field.

E.g:

SELECT * FROM information_schema.triggers WHERE TRIGGER_NAME='XXX';

(4) Restrictions

Conditional restrictions are very important for some occasions involving amounts (as mentioned in the opening paragraph), and will also be applied in the amount of e-commerce purchase restrictions.

Trigger uses delimiter, begin and if statement blocks to achieve the limit conditions.

例如:
mysql> delimiter //           
mysql> create trigger shop_limit before update on shoppingcar
    -> for each row
    -> begin
    ->   if new.amount>3 then
    ->      set new.amount=3;
    ->   elseif new.amount<0 then
    ->      set new.amount=0;
    ->   end if;
    -> end; //
mysql> delimiter ;

Conditional statement blocks are wrapped with begin and end

delimiter: switch the end character, because; is the default end character in MySQL, if the symbol appears in the program block, it will cause conflict. Finally, the terminator must be modified back. Note that there is a space between the delimiter and the terminator, otherwise it will not be possible to switch.

Before updating data:

update data:

mysql> update shoppingcar set amount=4 where u_id=1;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0

After updating the data:

Purchase volume cannot exceed 3

About triggers and transactions

For the transaction table (Innodb), the failure of the judgment statement following the before statement will cause all changes executed by the event statement to be rolled back . Failure of the trigger will cause the statement to fail, so failure of the trigger will also cause a rollback. For non-transactional tables (MyISAM), this type of rollback cannot be performed, so despite the statement failure, any changes performed before the point of error are still valid.

Restrictions on the use of triggers

The trigger has some limitations:

1. Triggers cannot use the CALL statement to return data to the client or use dynamic SQL stored procedures. However, the stored procedure is allowed to return data to the trigger through the OUT or INOUT parameters.

2. Trigger can not use transaction-related statements, such as START TRANSACTION, COMMIT or ROLLBACK. Because the trigger handles the update, delete, insert and other events, and is executed in the order of before, SQL statement, and after, once a certain step is wrong, the data will be rolled back. If transactions are used in triggers, conflicts will arise.

Guess you like

Origin www.linuxidc.com/Linux/2020-04/162980.htm