[英]PostgreSQL - insert rows based on select from another table, and update an FK in that table with the newly inserted rows
[英]How to use a newly inserted value from another table in PostgreSQL?
假设我有两个表final table
和table_1
,我想使用table_1
中的最新值,并在final_table
中使用触发器插入它们,每次INSERT ON table_1
。 当我如示例中所示创建触发器inserttrigger()
并创建触发器时,我得到最新值乘以table_1
中的行数。 如何正确编写触发器,使我只获得 table1 中的一条最新记录?
正在做:
-- 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.
我会推荐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();
请注意,您也可以使用 common-table-expression 和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.