UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$
DECLARE
BEGIN
UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2;
IF NOT FOUND THEN
INSERT INTO tableName values (value, arg1, arg2);
END IF;
END;
$$ LANGUAGE 'plpgsql';
WITH upsert AS (
UPDATE spider_count SET tally=tally+1
WHERE date='today' AND spider='Googlebot'
RETURNING *
)
INSERT INTO spider_count (spider, tally)
SELECT 'Googlebot', 1
WHERE NOT EXISTS (SELECT * FROM upsert)
create table urls (
url_id serial primary key,
url text unique,
content text,
last_analyzed timestamptz);
insert into urls(url) values('hello'),
('How'),('are'),
('you'),('doing');
通过创建过程,您还可以执行upsert。
CREATE OR REPLACE PROCEDURE upsert_url(_url text) LANGUAGE plpgsql
as $$
BEGIN
INSERT INTO URLs (url) values (_url)
ON CONFLICT (url)
DO UPDATE SET last_analyzed = NOW();
END
$$;
通过调用程序进行测试。
call upsert_url('I am is ok');
call upsert_url('hello');
5条答案
按热度按时间ohtdti5x1#
这已经被问过很多次了。可以在这里找到一个可能的解决方案:https://stackoverflow.com/a/6527838/552671
此解决方案需要
UPDATE
和INSERT
。在Postgres 9.1中,可以通过一个查询来实现:https://stackoverflow.com/a/1109198/2873507
tyky79it2#
如果
INSERTS
很少,我会避免执行NOT EXISTS (...)
,因为它在所有更新时都会发出SELECT
。看看wildpeaks的回答:https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql这样,Postgres最初会尝试执行
UPDATE
。如果没有行受到影响,它将返回到发出INSERT
。chy5wohz3#
我发现this post在这个场景中更相关:
xmakbtuz4#
首先尝试插入。如果在
url
列上存在冲突,则更新content和last_analyzed字段。如果更新很少,这可能是更好的选择。tp5buhyn5#
通过创建过程,您还可以执行upsert。
通过调用程序进行测试。