MySQL trigger: detect actual data changes
MySQL triggers are used to perform specific operations when data is modified. However, determining whether the data has actually changed becomes a challenge when only significant data changes trigger actions. The NEW
and OLD
keywords allow column-level comparisons, but in tables with many columns, relying on a single comparison can become tedious and error-prone.
Time stamp based triggering
One way to solve this problem is to utilize timestamps to determine if any data modification has occurred. MySQL automatically updates the timestamp column with the current time when a row is inserted or modified. By comparing the new and old timestamps we can determine if any changes were made.
Implementation method
To implement a trigger that only executes when actual data changes, consider the following steps:
NEW
and OLD
. The trigger action is only executed if the timestamps are different. <code class="language-sql">CREATE TABLE foo ( a INT, b INT, ts TIMESTAMP ); CREATE TRIGGER ins_sum AFTER UPDATE ON foo FOR EACH ROW BEGIN IF NEW.ts != OLD.ts THEN INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b); END IF; END;</code>
Example
In this example, the foo
table contains an additional ts
column to track timestamps. The ins_sum
trigger is configured to insert a record into the bar
table only when the timestamp of the updated row changes.
<code class="language-sql">-- 向'foo'表插入初始数据 INSERT INTO foo (a, b) VALUES (1, 1), (2, 2), (3, 3); -- 更新'foo'表,但未进行任何更改 UPDATE foo SET b = 3 WHERE a = 3; -- 验证触发器未执行 SELECT * FROM bar; -- 输出:空集(未检索到任何行) -- 使用实际更改更新'foo'表 UPDATE foo SET b = 4 WHERE a = 3; -- 验证触发器已执行 SELECT * FROM bar; -- 输出:包含数据的行(触发器操作已完成)</code>
Advantages of using timestamps
The above is the detailed content of How Can MySQL Triggers Efficiently Detect Actual Data Changes?. For more information, please follow other related articles on the PHP Chinese website!