mysql触发器示例 - 这可以更有效地完成吗?

时间:2012-12-18 19:24:32

标签: mysql triggers

我目前有两张表格如下:

数据表

+-----+-------------+---------------+
| uri | field1      | field2        |
+-----+-------------+---------------+
|   1 | word        | somethingelse |
|   2 | somethinge  | values        |
|   3 | change_this | test          |
+-----+-------------+---------------+

日志表

+--------+------+----------+-----------+-------------+---------------------+
| log_id | uri  | field_id | old_value | new_value   | modified_date       |
+--------+------+----------+-----------+-------------+---------------------+
|     14 | 3    | field1   | word32    | change_this | 2012-12-18 13:06:27 |
+--------+------+----------+-----------+-------------+---------------------+

当我更新field1或field2的值时,我在'log'表中得到一个条目,关于哪个字段被更改,从什么,什么,何时以及更新的记录的uri。

我的问题是关于触发器本身:它是否正常,还是可以更有效地完成?我老实说从来没有写过触发器,并根据谷歌发现的几个片段拼凑了这个。我欢迎您的想法/反馈。

DELIMITER $$
DROP TRIGGER IF EXISTS trig_update $$
CREATE TRIGGER trig_update AFTER UPDATE on data
FOR EACH ROW
BEGIN
DECLARE data_uri VARCHAR(32);
IF (NEW.field1 != OLD.field1) THEN
SET data_uri = (SELECT uri FROM data WHERE field1 = NEW.field1);
INSERT INTO log (uri, field_id, old_value, new_value, modified_date) 
VALUES (data_uri, "field1", OLD.field1, NEW.field1, NOW());
END IF; 
IF (NEW.field2 != OLD.field2) THEN
SET data_uri = (SELECT uri FROM data WHERE field2 = NEW.field2);
INSERT INTO log (uri, field_id, old_value, new_value, modified_date) 
VALUES (data_uri, "field2", OLD.field2, NEW.field2, NOW());
END IF; 
END$$
DELIMITER ;

1 个答案:

答案 0 :(得分:4)

您应该消除冗余查询:

DELIMITER $$
DROP TRIGGER IF EXISTS trig_update $$
CREATE TRIGGER trig_update AFTER UPDATE on data
FOR EACH ROW
BEGIN
IF (NEW.field1 != OLD.field1) THEN
  INSERT INTO log (uri, field_id, old_value, new_value, modified_date) 
  VALUES (NEW.uri, "field1", OLD.field1, NEW.field1, NOW());
END IF; 
IF (NEW.field2 != OLD.field2) THEN
  INSERT INTO log (uri, field_id, old_value, new_value, modified_date) 
  VALUES (NEW.uri, "field2", OLD.field2, NEW.field2, NOW());
END IF; 
END$$
DELIMITER ;