触发
一句话解释
触发是 存储 procedure 那个 fires automatically 当 INSERT, UPDATE, or DELETE occurs on 表.
用大白话说
trigger 是一种special kind of stored procedure that runs automatically when a specific event happens on a table。 You define the event (INSERT, UPDATE, or DELETE) and the timing (BEFORE or AFTER the event), and the trigger's code runs every time that event occurs.
Common uses for triggers:
- Audit logging: record every change to a table in an audit table.
- Enforcing complex rules: check conditions that cannot be expressed with simple constraints.
- Auto-updating timestamps: set
updated_atwhenever a row changes. - Cascading updates: update related data when a row changes.
Triggers are powerful but can make behavior hard to trace — changes happen "magically" without an explicit call. Use them sparingly and document them well.
示例
sql
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
NEW.updated_at = NOW();
END;
-- Now every UPDATE on users automatically sets updated_at这个触发 automatically 更新 updated_at 列 whenever 用户行 是修改.
相关术语
相关资源
相关课程
- 触发
学习如何 创建 and use 触发.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。