Postgresql使用触发器在插入值后更新列值

Nok*_*Nok 0 sql postgresql triggers sql-update sql-insert

我想将值插入到 tableA 中,然后更新列 [amount_hkd]。我已经成功使用触发器,但性能非常慢,应用触发器后需要一个小时才能完成 8400 行的插入。我怎样才能提高性能?感谢您的帮助

要执行的语句:

INSERT INTO tableA (suppliers, invoice_dates, shipment_dates, amounts, currency, currency_conversion_rate)
SELECT l.supplier, l.invoice_date, l.shipment_date, l.amount, l.currency, o.currency_conversion_rate
FROM tableB l
LEFT JOIN tableC o
ON l.currency = o.currency_code
WHERE l.supplier = 'ABC'
Run Code Online (Sandbox Code Playgroud)

我创建的函数:

CREATE OR REPLACE FUNCTION cal() 
RETURNS TRIGGER AS $$ 
BEGIN 
UPDATE tableA 
SET amount_hkd = NEW.amounts * NEW.currency_conversion_rate;
RETURN NEW; 
END; 
$$ LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)

我尝试的第一个触发器:

CREATE CONSTRAINT TRIGGER update_amount
AFTER INSERT ON tableA
DEFERRABLE
INITIALLY DEFERRED
FOR EACH ROW 
EXECUTE PROCEDURE cal();
Run Code Online (Sandbox Code Playgroud)

我尝试过的第二个触发器:

CREATE TRIGGER update_amount 
AFTER INSERT ON tableA
FOR EACH ROW 
EXECUTE PROCEDURE cal();
Run Code Online (Sandbox Code Playgroud)

Lau*_*lbe 6

插入行后更新该行的效率非常低。更好的方法是使用BEFORE可以在插入新行之前修改新行的触发器:

CREATE OR REPLACE FUNCTION cal() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN 
   NEW.amount_hkd := NEW.amounts * NEW.currency_conversion_rate;
   RETURN NEW; 
END;$$;

CREATE TRIGGER update_amount 
   BEFORE INSERT ON tableA FOR EACH ROW 
   EXECUTE PROCEDURE cal();
Run Code Online (Sandbox Code Playgroud)