如何在postgresql中使用另一个表中新插入的值?

hmmo2u0o  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(302)

假设我有两张table final table 以及 table_1 ,我要使用 table_1 然后用扳机插入 final_tableINSERT 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.
v1uwarro

v1uwarro1#

我推荐 VALUES() 语法:

CREATE OR REPLACE FUNCTION inserttrigger() 
RETURNS TRIGGER AS
$func$
BEGIN
    INSERT INTO final_table VALUES(NEW.id, NEW.value);
    RETURN NEW;                       
END;
$func$ language plpgsql;

CREATE TRIGGER final_table_update BEFORE INSERT ON table_1
FOR EACH ROW EXECUTE PROCEDURE inserttrigger();

请注意,您还可以使用公共表表达式和 returning 语法,避免了触发器的需要:

with t1 as (
    insert into table_1(id, value_fin) values(4, 215)
    returning id, value_fin
)
insert into final_table(id, value) select id, value_fin from t1

相关问题