![](/img/trans.png)
[英]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.