Postgres 9.5 ON CONFLICT DO SELECT

前端 未结 1 1262
名媛妹妹
名媛妹妹 2021-01-13 09:02

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:

         


        
1条回答
  •  时光说笑
    2021-01-13 09:41

    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

    0 讨论(0)
提交回复
热议问题