search
HomeDatabaseMysql TutorialDetailed explanation of triggers in MySQL learning summary

This article brings you relevant knowledge about mysql, which mainly introduces related issues about triggers. Triggers are a special stored procedure, triggers and stored procedures. The same is a function that can complete specific functions and storage. I hope it will be helpful to everyone.

Detailed explanation of triggers in MySQL learning summary

Recommended learning: mysql tutorial

Trigger

1. Introduction to triggers

Trigger is a special stored procedure. A trigger, like a stored procedure, is a SQL segment that can complete a specific function and is stored on the database server. However, the trigger does not need to be called when performing DML operations on the data in the data table. The execution of this SQL segment is automatically triggered when

, no need to call it manually.

In MySQL, only the insert\delete\update operation can trigger the execution of the trigger.

2. Trigger usage

1.Create trigger

create trigger tri_name   -- tri_name:触发器别名
<before> 						-- 定义触发时机
<insert>		-- 定义DML类型
ON <table_name>						-- 要触发的表
for each <row>							
-- for each row 声明为⾏级触发器(操作的每⼀条记录就触发触发器执⾏⼀次)
-- for each statement 声明语句级触发器(触发动作体执行一次)
begin											-- 当只有一句sql语句时,begin...end 可以省略	
	sql_statement 					-- 进行触发器对应的DML类型的操作
end;


#示例
-- 创建触发器:当学⽣信息表发⽣添加操作时,则向⽇志信息表中记录⼀条⽇志
create trigger tri_test1
after insert on students
for each row
insert into stulogs(time,log_text) values(now(), concat('添 加',NEW.stu_num,'学⽣信息'));</row></table_name></insert></before>

2.View trigger

#查看全部触发器
show triggers;

#查看触发器的创建语句
show create trigger 触发器名字;

3. Delete trigger

Triggers cannot be modified, only deleted

drop trigger  触发器名字;

3. NEW and OLD

Triggers are used to monitor insert, delete, and update operations on data in the data table. Triggers usually handle

some DML related operations; we can use the NEW and OLD keywords to trigger Get the data of the DML operation that triggers this trigger

NEW: used in the trigger to get the data added by the insert operation and modified by the update operation Record
  • OLD: Used in triggers to obtain the data before delete operation and data before update operation modification
  • 1. Use of NEW
#insert操作中:NEW表示添加的新记录
create trigger tri_test1
after insert on students
for each row
insert into stulogs(time,log_text) values(now(), concat('添 加',NEW.stu_num,'学⽣信息'));


#update操作中:NEW 表示修改后的数据
-- 创建触发器 : 在监听update操作的触发器中,可以使⽤NEW获取修改后的数据
create trigger tri_test2
after update on students for each row
insert into stulogs(time,log_text) values(now(), concat('修改学⽣信息
为:',NEW.stu_num,NEW.stu_name));

2. Use of OLD

#delete操作中:OLD表示删除的记录
create trigger tri_test3
after delete on students for each row
insert into stulogs(time,log_text) values(now(), concat('删 除',OLD.stu_num,'学⽣信息')); 


#update操作中:OLD表示修改前的记录
create trigger tri_test2
after update on students for each row
insert into stulogs(time,log_text) values(now(), concat('将学⽣姓名从
【',OLD.stu_name,'】修改为【',NEW.stu_name,'】'));

IV. 10.4 Summary of trigger usage

1. Advantages

Triggers are automatically executed Yes, it is executed immediately when the corresponding DML operation is executed on the table related to the trigger;
  • Triggers can implement cascading operations (association operations) of data in the table, which is beneficial to ensuring the integrity of the data. Integrity;
  • Triggers can perform more complex legality verification on DML operation data
  • 2. Disadvantages

Usage If there is a problem with the business logic implemented by the trigger, it will be difficult to locate and later maintenance will be difficult;
  • Extensive use of triggers can easily lead to a messy code structure and increase the complexity of the program;
  • When triggered When the amount of data operated by the processor is relatively large, the execution efficiency will be greatly reduced.
  • 3. Usage suggestions

In Internet projects, you should avoid adapting triggers;

For projects with small concurrency, you can choose to use Use stored procedures, but the use of stored procedures is not recommended in Internet references

(Reason: when storing procedures, the logic of business implementation is handed over to the database for processing, which increases or decreases the load on the database; Not conducive to database migration)

Recommended learning:

mysql learning tutorial

The above is the detailed content of Detailed explanation of triggers in MySQL learning summary. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
MySQL String Types: Storage, Performance, and Best PracticesMySQL String Types: Storage, Performance, and Best PracticesMay 10, 2025 am 12:02 AM

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

Understanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreUnderstanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreMay 10, 2025 am 12:02 AM

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

What are the String Data Types in MySQL?What are the String Data Types in MySQL?May 10, 2025 am 12:01 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

See all articles

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version