This article brings you relevant knowledge about mysql, which mainly introduces related issues about triggers, including what is a trigger, how to create a trigger in the database, and trigger Whether the device can replace foreign keys, let's take a look at it. I hope it will be helpful to everyone.
Recommended learning: mysql video tutorial
Concept: Trigger is a method provided by SQL server to programmers and data analysts to ensure data integrity. It is related to table events. The execution of a special stored procedure is not called by a program or started manually, but is triggered by events. For example, its execution is activated when a table is operated (insert, delete, update). Triggers are often used to enforce data integrity constraints and business rules. Triggers can be found in the DBA_TRIGGERS and USER_TRIGGERS data dictionaries. A SQL3 trigger is a statement that can be automatically executed by the system to modify the database.
Example 1: Create a user table (user ID, user name) and create a trigger (when data is inserted into the user table, a globally unique ID is automatically generated)
Create the user table first
create table user( id int PRIMARY KEY, name varchar(20) );
Create a trigger
-- 建立触发器名为tt create TRIGGER tt -- 触发条件,向user表中插入数据时启动触发器 BEFORE insert on user -- 检查表中每一行,对新插入的数据进行操作 for EACH ROW -- 执行操作 BEGIN set new.id=UUID(); END
The trigger just created (View the code show triggers of all triggers under the current database)
Effect: Insert three user names into the table and automatically generate three IDs
insert user(name) VALUE('张三'),('李四'),('王五')
Example 2: Create an order table DD (order ID, product name, user ID), and create a trigger tq1 (when a user is deleted, the The user's order will also be deleted)
Create table
create table DD( ddid int PRIMARY KEY, ddname VARCHAR(20), userid VARCHAR(50) )
Create trigger
delimiter $ -- 建立触发器名为tq create TRIGGER tq1 -- 触发条件,再dd表删除数据之后启动触发器 AFTER DELETE on user -- 检查表中每一行,对新插入的数据进行操作 for EACH ROW -- 执行操作 BEGIN DELETE FROM dd WHERE old.id=userid; END $ delimiter ;
Add two pieces of data to the table
Effect: Delete the user in the user table, and the records in the dd table will also follow Delete
Delete Zhang San
delete from user WHERE name='张三'
Summary: Triggers can replace foreign keys at certain times, but not in all situations. Foreign keys and triggers can also be used together
Recommended learning:The above is the detailed content of Let's talk about MYSQL database triggers. For more information, please follow other related articles on the PHP Chinese website!