触发器是与表相关联的命名数据库对象,当表发生特定事件时会被激活。触发器的一些用途是对要插入到表中的值进行检查,或者对更新中涉及的值进行计算。A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.
触发器被定义为在语句插入、更新或删除关联表中的行时激活。这些行操作就是触发事件。例如,行可以通过INSERT或LOAD
DATA语句插入,并且插入触发器会在每个插入的行上激活。触发器可以设置为在触发事件发生之前或之后激活。例如,你可以设置触发器在每行插入到表中之前激活,或者在每行更新之后激活。A trigger is defined to activate when a statement inserts, updates,
or deletes rows in the associated table. These row operations are
trigger events. For example, rows can be inserted by
INSERT or LOAD
DATA statements, and an insert trigger activates for each
inserted row. A trigger can be set to activate either before or
after the trigger event. For example, you can have a trigger
activate before each row that is inserted into a table or after each
row that is updated.
MySQL 触发器仅在通过 SQL 语句对表进行更改时才会激活。这包括对可更新视图所依赖的基础表的更改。对于通过不将 SQL 语句发送到 MySQL 服务器的 API 对表进行的更改,触发器不会激活。这意味着使用 NDB API 进行的更新不会触发触发器。MySQL triggers activate only for changes made to tables by SQL
statements. This includes changes to base tables that underlie
updatable views. Triggers do not activate for changes to tables
made by APIs that do not transmit SQL statements to the MySQL
Server. This means that triggers are not activated by updates made
using the NDB API.
对 INFORMATION_SCHEMA 或 performance_schema 表的更改不会激活触发器。这些表实际上是视图,并且不允许在视图上使用触发器。Triggers are not activated by changes in
INFORMATION_SCHEMA or
performance_schema tables. Those tables are
actually views and triggers are not permitted on views.
以下各节描述了创建和删除触发器的语法,演示了如何使用触发器的一些示例,并说明了如何获取触发器的元数据。The following sections describe the syntax for creating and dropping triggers, show some examples of how to use them, and indicate how to obtain trigger metadata.
附加资源Additional Resources
在使用触发器时,您可能会发现MySQL 用户论坛很有帮助。You may find the MySQL User Forums helpful when working with triggers.
有关 MySQL 中触发器的常见问题的答案,请参阅A.5 节,“MySQL 8.4 FAQ:触发器”。For answers to commonly asked questions regarding triggers in MySQL, see Section A.5, “MySQL 8.4 FAQ: Triggers”.
触发器的使用有一些限制;请参阅27.8 节,“存储程序的限制”。There are some restrictions on the use of triggers; see Section 27.8, “Restrictions on Stored Programs”.
触发器的二进制日志记录如27.7 节,“存储程序二进制日志记录”中所述。Binary logging for triggers takes place as described in Section 27.7, “Stored Program Binary Logging”.