Postgres 9.5 ON CONFLICT DO SELECT

时间:2018-04-01 11:44:06

标签: sql postgresql postgresql-9.5

在Postgres 9.5中进行UPSERT时,是否可以在INSERT成功时返回null并返回ON CONFLICT?

我想这样的事情:

insert into "user" (timestamp, user_id, member_id) 
values ($1, $2, $3)
ON CONFLICT (user_id, member_id) 
DO select id from "user" where user_id = $2 returning user_id

选择user_id的唯一目的是在CONFLICT上返回一些东西(除null以外的任何东西),而不写入磁盘。我知道这可以通过ON CONFLICT DO UPDATE来完成,但它会涉及写入磁盘。

1 个答案:

答案 0 :(得分:4)

您可以使用CTE:

WITH cte AS (
   INSERT INTO "user"(timestamp, user_id, member_id)
   values ($1, $2, $3)
   ON CONFLICT (user_id, member_id) DO NOTHING
   RETURNING user_id
)
SELECT NULL AS result
WHERE EXISTS (SELECT 1 FROM cte)          -- success
UNION ALL
SELECT id 
FROM "user" 
WHERE user_id = $2 
  AND NOT EXISTS (SELECT 1 FROM cte);     -- conflict

<强> DBFiddle Demo