Problems with a PostgreSQL upsert query

喜你入骨 提交于 2019-12-04 14:33:15
Erwin Brandstetter

The UPDATE in the first CTE updated produces no row. That means, you don't get a NULL value for updated.id either. When joining to updated, you get nothing, so no INSERT happens either.

Should work with NOT EXISTS:

WITH updated AS (
   UPDATE vote_user_table v
   SET    positive = TRUE       -- use booleann values ..
         ,negative = FALSE      -- .. instead of quoted string literals
   FROM   usuario u
   WHERE  v.review_id = 6       -- guessing origin
   AND    v.user_id = u.id
   AND    u.username ILIKE 'aaa@aaa.com'
   RETURNING v.id
   )
INSERT INTO vote_user_table (review_id, user_id, positive, negative)
SELECT 6, u.id, TRUE, FALSE
FROM   usuario u
WHERE NOT EXISTS (SELECT 1 FROM updated)
AND    u.username ILIKE 'aaa@aaa.com';

Be aware that there is still a very tiny chance for a race condition under heavy concurrent load. Details under this related question:
Upsert with a transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!