假设我有两张table final table
以及 table_1
,我要使用 table_1
然后用扳机插入 final_table
每 INSERT ON table_1
. 当我创建trigger函数时 inserttrigger()
如示例所示并创建触发器,我得到的最新值乘以 table_1
. 如何正确地编写触发器,使我只得到表1中的一条最新记录?
正在执行:
-- Create tables and inserting example values
CREATE TABLE final_table(id INTEGER, value_fin INTEGER);
CREATE TABLE table_1(id INTEGER, value INTEGER);
INSERT INTO table_1 VALUES(1, 200), (2,203), (3, 209);
-- Create Triggerfunction
CREATE OR REPLACE FUNCTION inserttrigger()
RETURNS TRIGGER AS
$func$
BEGIN
INSERT INTO final_table
SELECT latest.id, latest.value
FROM (SELECT NEW.id, NEW.value FROM table_1) AS latest;
RETURN NEW;
END;
$func$ language plpgsql;
-- Create Trigger
CREATE TRIGGER final_table_update BEFORE INSERT ON table_1
FOR EACH ROW EXECUTE PROCEDURE inserttrigger() ;
--Insert example values
INSERT INTO table_1 VALUES(4, 215);
结果:
SELECT * FROM final_table
id | value_fin
4 215
4 215
4 215
但应该是这样的:
id | value_fin
4 215
而:
CREATE TRIGGER final_table_update BEFORE INSERT ON table_1
EXECUTE PROCEDURE inserttrigger() ;
结果:
ERROR: record "new" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
1条答案
按热度按时间v1uwarro1#
我推荐
VALUES()
语法:请注意,您还可以使用公共表表达式和
returning
语法,避免了触发器的需要: