2

我目前有两个表如下:

数据表

+-----+-------------+---------------+
| 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 两个的值时,我会在“日志”表中获得一个条目,说明哪个字段已更改,从什么更改为什么,何时更改,以及更新记录的 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 ;
4

1 回答 1

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 ;
于 2012-12-18T19:36:29.550 回答