Insert, on duplicate update in PostgreSQL?

前端 未结 16 2307
别那么骄傲
别那么骄傲 2020-11-21 04:52

Several months ago I learned from an answer on Stack Overflow how to perform multiple updates at once in MySQL using the following syntax:

INSERT INTO table          


        
16条回答
  •  面向向阳花
    2020-11-21 05:54

    With PostgreSQL 9.1 this can be achieved using a writeable CTE (common table expression):

    WITH new_values (id, field1, field2) as (
      values 
         (1, 'A', 'X'),
         (2, 'B', 'Y'),
         (3, 'C', 'Z')
    
    ),
    upsert as
    ( 
        update mytable m 
            set field1 = nv.field1,
                field2 = nv.field2
        FROM new_values nv
        WHERE m.id = nv.id
        RETURNING m.*
    )
    INSERT INTO mytable (id, field1, field2)
    SELECT id, field1, field2
    FROM new_values
    WHERE NOT EXISTS (SELECT 1 
                      FROM upsert up 
                      WHERE up.id = new_values.id)
    

    See these blog entries:

    • Upserting via Writeable CTE
    • WAITING FOR 9.1 – WRITABLE CTE
    • WHY IS UPSERT SO COMPLICATED?

    Note that this solution does not prevent a unique key violation but it is not vulnerable to lost updates.
    See the follow up by Craig Ringer on dba.stackexchange.com

提交回复
热议问题