带有WHERE子句的PostgreSQL ON CONFLICT

时间:2017-06-15 15:49:59

标签: sql postgresql sql-insert upsert

Postgres文档使得看起来WHERE子句可以作为ON CONFLICT条件:https://www.postgresql.org/docs/9.5/static/sql-insert.html

我无法使其正常工作(如果可能的话)。这是我尝试过的众多排列中的一种:

INSERT INTO friends (id, dob, frn, status, "groupId", 
"createdAt", "updatedAt") 
VALUES ('1da04305-68ef-4dc1-be6c-
826ab83a6479', '1937-06-01T08:29:08-07:00', 100001, 'New', 'bc1567bc-
14ff-4ba2-b108-4cb2e0f0f768', NOW(), NOW()) 
ON CONFLICT 
    WHERE frn=100001 DO NOTHING

frn没有任何约束,因此语法更简单:

ON CONFLICT (frn) DO NOTHING

抛出数据库错误。我希望这是一个简单的语法问题。

1 个答案:

答案 0 :(得分:1)

WHERE子句从属于ON CONFLICT (constraint) DO UPDATE SET ...子句。它只查看在尝试INSERT时违反指定约束的单行。

一个语法上有效的例子:

INSERT INTO friends (id, dob, frn, status, "groupId", 
    "createdAt", "updatedAt") 
VALUES ('1da04305-68ef-4dc1-be6c-826ab83a6479',
    '1937-06-01T08:29:08-07:00', 100001, 'New',
    'bc1567bc-14ff-4ba2-b108-4cb2e0f0f768', NOW(), NOW()) 
ON CONFLICT ("groupId", frn) DO UPDATE SET
        status='Revised', "updatedAt"=NOW()
    WHERE status<>'Deleted';