gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:43:14 25 4
gpt4 key购买 nike

我目前有两个表如下:

数据表

+-----+-------------+---------------+
| 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 ;

最佳答案

您应该消除冗余查询:

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 ;

关于mysql 触发器示例 - 这可以更有效地完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13940033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com