How to use trigger in MySQL database
1. Basic concepts
A trigger is a special type of stored procedure. A trigger is triggered by an event. Execution of
trigger trigger is similar to js events
1. Function
Forcibly check or convert data before writing to the data table (to ensure data security )
When a trigger error occurs, the result of the change will be revoked (transaction safety)
Some database management systems can define language for data DDL uses triggers, called DDL triggers
You can replace the change instructions instead of according to specific situations (mysql does not support)
2. Advantages and Disadvantages of Triggers
2.1. Advantages
Triggers can achieve cascading changes through related tables in the database (if the data of a table changes , you can use triggers to implement operations on other tables, the user does not know)
Ensure data security and perform security verification
- Excessive reliance on triggers will inevitably affect the structure of the database and increase the complexity of maintenance
- Making the data unavailable at the program level Control
create trigger 触发器名字 触发时机 触发事件 on 表 for each row
begin
end
Copy after login
2. Trigger objectcreate trigger 触发器名字 触发时机 触发事件 on 表 for each row begin end
on table for each row The trigger binds all rows in the table. When no specified change occurs in a row, the trigger will be triggered
- before : The state before the data changes
- after: The state after the data has changed
- inert insert operations
- update Update operation
- delete operation
before insert after insert before update after update before delete after delete
Requirements:
Place an order to reduce inventoryThere are two tables, one is the product table and the other is the order table (retaining the product ID) for each order generated, the corresponding inventory in the product table should changeCreate two tables:
create table my_item( id int primary key auto_increment, name varchar(20) not null, count int not null default 0 ) comment '商品表'; create table my_order( id int primary key auto_increment, item_id int not null, count int not null default 1 ) comment '订单表'; insert my_item (name, count) values ('手机', 100),('电脑', 100), ('包包', 100); mysql> select * from my_item; +----+--------+-------+ | id | name | count | +----+--------+-------+ | 1 | 手机 | 100 | | 2 | 电脑 | 100 | | 3 | 包包 | 100 | +----+--------+-------+ 3 rows in set (0.00 sec) mysql> select * from my_order; Empty set (0.02 sec)
Create trigger:
If data insertion occurs in the order table, the corresponding product should be reduced in inventorydelimiter $$ create trigger after_insert_order_trigger after insert on my_order for each row begin -- 更新商品库存 update my_item set count = count - 1 where id = 1; end $$ delimiter ;
-- 查看所有触发器
show triggers\G
*************************** 1. row ***************************
Trigger: after_insert_order_trigger
Event: INSERT
Table: my_order
Statement: begin
update my_item set count = count - 1 where id = 1;
end
Timing: AFTER
Created: 2022-04-16 10:00:19.09
sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
Definer: root@localhost
character_set_client: utf8mb4
collation_connection: utf8mb4_general_ci
Database Collation: utf8mb4_general_ci
1 row in set (0.00 sec)
-- 查看创建语句
show crate trigger 触发器名字;
-- eg:
show create trigger after_insert_order_trigger;
Copy after login
4. Trigger the triggerLet the trigger execute , let the corresponding operation occur at the corresponding time in the table specified by the trigger-- 查看所有触发器 show triggers\G *************************** 1. row *************************** Trigger: after_insert_order_trigger Event: INSERT Table: my_order Statement: begin update my_item set count = count - 1 where id = 1; end Timing: AFTER Created: 2022-04-16 10:00:19.09 sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION Definer: root@localhost character_set_client: utf8mb4 collation_connection: utf8mb4_general_ci Database Collation: utf8mb4_general_ci 1 row in set (0.00 sec) -- 查看创建语句 show crate trigger 触发器名字; -- eg: show create trigger after_insert_order_trigger;
insert into my_order (item_id, count) values(1, 1); mysql> select * from my_order; +----+---------+-------+ | id | item_id | count | +----+---------+-------+ | 1 | 1 | 1 | +----+---------+-------+ 1 row in set (0.00 sec) mysql> select * from my_item; +----+--------+-------+ | id | name | count | +----+--------+-------+ | 1 | 手机 | 99 | | 2 | 电脑 | 100 | | 3 | 包包 | 100 | +----+--------+-------+ 3 rows in set (0.00 sec)
drop trigger 触发器名字;
-- eg
drop trigger after_insert_order_trigger;
Copy after login
6. Application of the triggerRecord keywords new old6. ImproveAutomatic inventory deduction for productsThe trigger targets each record in the data table, and each row of data has a corresponding one before and after the operation. The statusdrop trigger 触发器名字; -- eg drop trigger after_insert_order_trigger;
The trigger obtains the corresponding data status before execution:
- Save the data status before there is any operation to The status after the
old
keyword in the
- operation is placed in
new
Basic syntax:
Keyword.Field nameNot all triggers of old and new have
- insert is empty before inserting, and there is no old
- delete clear Data, no new
Item automatically deducts inventory:
delimiter $$ create trigger after_insert_order_trigger after insert on my_order for each row begin -- 通过new关键字获取新数据的id 和数量 update my_item set count = count - new.count where id = new.item_id; end $$ delimiter ;
Trigger trigger:
mysql> select * from my_order; +----+---------+-------+ | id | item_id | count | +----+---------+-------+ | 1 | 1 | 1 | +----+---------+-------+ mysql> select * from my_item; +----+--------+-------+ | id | name | count | +----+--------+-------+ | 1 | 手机 | 99 | | 2 | 电脑 | 100 | | 3 | 包包 | 100 | +----+--------+-------+ insert into my_order (item_id, count) values(2, 3); mysql> select * from my_order; +----+---------+-------+ | id | item_id | count | +----+---------+-------+ | 1 | 1 | 1 | | 2 | 2 | 3 | +----+---------+-------+ mysql> select * from my_item; +----+--------+-------+ | id | name | count | +----+--------+-------+ | 1 | 手机 | 99 | | 2 | 电脑 | 97 | | 3 | 包包 | 100 | +----+--------+-------+
What should I do if the inventory quantity is not as large as the product order?
-- 删除原有触发器 drop trigger after_insert_order_trigger; -- 新增判断库存触发器 delimiter $$ create trigger after_insert_order_trigger after insert on my_order for each row begin -- 查询库存 select count from my_item where id = new.item_id into @count; -- 判断 if new.count > @count then -- 中断操作,暴力抛出异常 insert into xxx values ('xxx'); end if; -- 通过new关键字获取新数据的id 和数量 update my_item set count = count - new.count where id = new.item_id; end $$ delimiter ;
Result verification:
mysql> insert into my_order (item_id, count) values(3, 101); ERROR 1146 (42S02): Table 'mydatabase2.xxx' doesn't exist mysql> select * from my_order; +----+---------+-------+ | id | item_id | count | +----+---------+-------+ | 1 | 1 | 1 | | 2 | 2 | 3 | +----+---------+-------+ 2 rows in set (0.00 sec) mysql> select * from my_item; +----+--------+-------+ | id | name | count | +----+--------+-------+ | 1 | 手机 | 99 | | 2 | 电脑 | 97 | | 3 | 包包 | 100 | +----+--------+-------+ 3 rows in set (0.00 sec)
The above is the detailed content of How to use trigger in MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.
