How to create and use triggers in MySQL.
In MySQL, you can use the CREATE TRIGGER statement to create a trigger. Triggers can perform specific actions on a particular table, such as triggering certain actions when inserting, updating, or deleting records.
Here is an example demonstrating how to create a trigger that fires when a record is inserted:
CREATE TRIGGER my_trigger
BEFORE INSERT ON my_table
FOR EACH ROW
BEGIN
-- 在此处编写需要执行的操作
INSERT INTO log_table (message) VALUES ('A new record was inserted');
END;
In this example, we have created a trigger named my_trigger, which will be triggered before inserting a record into my_table. The operation in the trigger is to insert a log record into log_table.
To activate the trigger, you can use the following statement:
INSERT INTO my_table (column1, column2) VALUES ('value1', 'value2');
When the above insertion operation is performed, triggers will be triggered and relevant operations will be executed.
You can use the following statement to view the triggers that have been created.
SHOW TRIGGERS;
To delete a trigger, you can use the following statement:
DROP TRIGGER my_trigger;
Triggers can be used to automate operations in the database, enhancing data consistency and integrity.