我已经阅读了Postgresql中不同的UPSERT实现,但所有这些解决方案相对较旧或相对具有异国情调(例如,使用
writeable CTE).
而且我根本不是一个psql专家,立刻就会发现,这些解决方案是否老旧,因为它们是推荐的,或者它们(好吧,几乎所有都是)只是不适合生产使用的玩具示例.
Postgresql现在有
UPSERT.
根据a similar StackOverflow question的优选方法目前如下:
CREATE TABLE db (a INT PRIMARY KEY,b TEXT); CREATE FUNCTION merge_db(key INT,data TEXT) RETURNS VOID AS $$ BEGIN LOOP -- first try to update the key UPDATE db SET b = data WHERE a = key; IF found THEN RETURN; END IF; -- not there,so try to insert the key -- if someone else inserts the same key concurrently,-- we could get a unique-key failure BEGIN INSERT INTO db(a,b) VALUES (key,data); RETURN; EXCEPTION WHEN unique_violation THEN -- do nothing,and loop to try the UPDATE again END; END LOOP; END; $$ LANGUAGE plpgsql; SELECT merge_db(1,'david'); SELECT merge_db(1,'dennis');