Home Database Mysql Tutorial 【MySQL 12】Trigger

【MySQL 12】Trigger

Feb 04, 2017 pm 01:40 PM

Trigger is a special type of stored procedure, which is different from the stored procedures we introduced before. Triggers are mainly triggered by events and are automatically called and executed. Stored procedures can be called by the name of the stored procedure.
The main function of triggers is to achieve data integrity and consistency between two or more tables that are more complex than referential integrity, thereby ensuring that changes in data in the tables comply with the determination of the database designer. business rules.
A special stored procedure that is automatically executed when a trigger inserts, updates, or deletes a table. Triggers are generally used on constraints with more complex check constraints.
The difference between triggers and ordinary stored procedures is that triggers operate on a certain table. During operations such as update, insert, and delete, the system will automatically call and execute the corresponding trigger on the table.
Triggers in SQL Server 2005 can be divided into two categories: DML triggers and DDL triggers. DDL triggers affect a variety of data definition language statements and are triggered. These statements include create, alter, and drop statements.

DML triggers are divided into:

1. after trigger (triggered after)
a. insert trigger
b. update trigger
c. delete trigger Trigger
2. Instead of trigger (triggered before)
3. Difference
After trigger: It is required that the trigger will be triggered only after a certain operation insert, update, delete is performed, and can only be defined in on the table.
Instead of trigger: It means that it does not execute its defined operations (insert, update, delete) but only executes the trigger itself. Instead of triggers, you can define them on the table or on the view.

inserted table and deleted table

When using triggers, SQL Server will create two special temporary tables for each trigger, namely the inserted table and the deleted table. These two tables are stored in memory and have the same structure as the table where the trigger was created. They are maintained and managed by the system and users are not allowed to modify them. Each trigger can only access its own temporary table. After the trigger is executed, the two tables will be automatically released.
(1) The inserted table is used to store copies of rows affected by insert or update statements. When an insert or update operation is performed, new data rows are added to both the base table and the inserted table that activate the trigger.
(2) The deleted table is used to store copies of rows affected by delete or update statements. When a delete or update operation is performed, the specified original data row is deleted from the base table and then transferred to the deleted table. Generally speaking, the same data rows will not exist in the base table and the deleted table.
Description:
The update operation is divided into two steps: first, transfer the modified original data rows in the basic table to the deleted table, and then copy the modified new data rows from the inserted table to the basic table. In other words, for the update operation, the deleted table stores the old value before modification, and the inserted table stores the new value after modification.

Four elements of trigger creation syntax:

1.监视地点(table) 
2.监视事件(insert/update/delete) 
3.触发时间(after/before) 
4.触发事件(insert/update/delete)
Copy after login

Syntax:

delimiter &&create trigger trigger
Nameafter/before insert/update/delete on 表名
for each row   #这句话在mysql是固定的
beginsql语句;
end&&
Copy after login

Product table

mysql> create table g(
    -> id int auto_increment primary key,    -> name varchar(10),    -> num int    -> );
Copy after login

Order table

mysql> create table o(
    -> idd int auto_increment primary key,    -> gid int,    -> much int    -> );
Copy after login

Insert product:

mysql> insert into g (name,num) value ('juzi',20);mysql> select * from g;
+----+------+------+| id | name | num  |
+----+------+------+|  3 | juzi |   20 |
+----+------+------+
Copy after login

If we did not use triggers: Suppose we now sell 3 items 1, we need to do two things

1. Insert a record into the order table

insert into o(gid,much) values(1,3);
Copy after login

2. Update the remaining quantity of product 1 in the product table

update g set num=num-3 where id=1;
Copy after login

Create trigger:

delimiter &
mysql> create trigger trg1
    -> after insert on o    -> for each row    -> begin    -> update g set num = num -3 where id = 1;    -> end&
Copy after login

Execution:

insert into o(gid,much) values(1,3)$
Copy after login
Copy after login


Result:

You will find that the quantity of product 1 has changed to 7, which means that when we insert an order, the trigger automatically performs the update operation for us.

But now there is a problem, because the num and id in our trigger are hard-coded, so no matter which product we buy, the quantity of product 1 will be updated in the end. For example: we insert another record into the order table: insert into o(gid,much) values(2,3). After execution, we will find that the quantity of product 1 has changed to 4, but the quantity of product 2 has not changed. This is obviously not the case. the results we want. We need to change the trigger we created earlier.

How do we reference the value of the row in the trigger, that is to say, we need to get the value of gid or much in our newly inserted order record.

For insert, the newly inserted row is represented by new, and the value of each column in the row is represented by new.column name.

So now we can change our trigger like this

create trigger tg2 
after insert on o 
for each row 
begin 
update g set num=num-new.much where id=new.gid;(注意此处和第一个触发器的不同) 
end$
Copy after login

The second trigger is created, let’s delete the first trigger first

drop trigger tg1$

Let’s test it again and insert an order record: insert into o(gid,much) values(2,3)$

After execution, it is found that the quantity of product 2 has changed to 7. That's right now.

There are still two situations:

1.当用户撤销一个订单的时候,我们这边直接删除一个订单,我们是不是需要把对应的商品数量再加回去呢?

2.当用户修改一个订单的数量时,我们触发器修改怎么写?

我们先分析一下第一种情况:

监视地点:o表

监视事件:delete

触发时间:after

触发事件:update

对于delete而言:原本有一行,后来被删除,想引用被删除的这一行,用old来表示,old.列名可以引用被删除的行的值。

那我们的触发器就该这样写:

create trigger tg3
after delete on o
for each row
begin
update g set num = num + old.much where id = old.gid;(注意这边的变化)
end$
Copy after login

创建完毕。

再执行

delete from o where oid = 2$
Copy after login

会发现商品2的数量又变为10了。

第二种情况:

监视地点:o表

监视事件:update

触发时间:after

触发事件:update

对于update而言:被修改的行,修改前的数据,用old来表示,old.列名引用被修改之前行中的值;

修改的后的数据,用new来表示,new.列名引用被修改之后行中的值。

那我们的触发器就该这样写:

create trigger tg4
after update on o
for each row
begin
update g set num = num+old.much-new.much where id = old/new.gid;
end$
Copy after login

先把旧的数量恢复再减去新的数量就是修改后的数量了。

我们来测试下:先把商品表和订单表的数据都清掉,易于测试。

假设我们往商品表插入三个商品,数量都是10,

买3个商品1:

insert into o(gid,much) values(1,3)$
Copy after login
Copy after login

这时候商品1的数量变为7;

我们再修改插入的订单记录:

update o set much = 5 where oid = 1$
Copy after login

我们变为买5个商品1,这时候再查询商品表就会发现商品1的数量只剩5了,说明我们的触发器发挥作用了。

以上就是 【MySQL 12】触发器的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles