问题
While doing UPSERT in Postgres 9.5, is it possible to return null on INSERT success and return something ON CONFLICT?
I would like to something like this:
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
The only purpose of selecting user_id is to return something (anything other than null) ON CONFLICT, and without writing to disk. I know that this can be done with ON CONFLICT DO UPDATE but it would involve writing to disk.
回答1:
You could use 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
来源:https://stackoverflow.com/questions/49597668/postgres-9-5-on-conflict-do-select