我想将对我的working
表的更改记录到我的history
表中,但前提是值在UPDATE 期间发生了更改,我尝试创建一个update_history 触发器,但它无论值是否已更改,都会添加一行,例如,假设我的工作表中有这个:
shift_id|site |organisational_unit
--------|---------|-------------------
123475|site01 |my org
如果我执行更新查询
UPDATE working SET site = $1, organisational_unit = $2 WHERE shift_id=$3', ['site01', 'my new org', '123475']
这会在历史表中为 site
创建一行,甚至认为它没有改变值我只想为 organisational_unit 更改创建一个新行
historyid|shiftid|fieldname |oldvalue |newvalue |updatedat |
---------|-------|-------------------|---------|-----------|-------------------|
7| 123475|organisational_unit|my org |my new org |2019-07-01 10:21:19|
8| 123475|site |site01 |site01 |2019-07-01 10:21:19|
我的触发器看起来像这样
-- create function for updates to track history
CREATE function update_history ()
RETURNS TRIGGER
as $$
BEGIN
-- check if data in column has changed between the update
IF NEW.client_id <> OLD.client_id THEN
-- if it has insert a row to the history table detailing the changes
INSERT INTO history (ShiftId, fieldName, OldValue, NewValue)
VALUES(New.shift_id, 'client id ', OLD.client_id, NEW.client_id);
-- if nothing has changed don't do anything
END IF;
IF NEW.organisational_unit <> OLD.organisational_unit THEN
INSERT INTO history (ShiftId, fieldName, OldValue, NewValue)
VALUES(New.shift_id, 'organisational_unit', OLD.organisational_unit, NEW.organisational_unit);
END IF;
IF NEW.site <> OLD.site THEN
INSERT INTO history
(ShiftId, fieldName, OldValue, NewValue)
VALUES(New.shift_id, 'site', OLD.site, NEW.site);
END IF;
return null;
END;
$$
language plpgsql;
最佳答案
最有效的方法是定义一个仅在某些列更改时触发的触发器:
CREATE TRIGGER ... BEFORE UPDATE ON ... FOR EACH ROW
WHEN (NEW IS DISTINCT FROM OLD)
EXECUTE FUNCTION update_history();
这避免了在不必要的情况下执行函数。
关于postgresql如何在没有任何变化的情况下停止触发添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56867543/