Insert, on duplicate update in PostgreSQL?

前端 未结 16 2236
别那么骄傲
别那么骄傲 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:33

    There is no simple command to do it.

    The most correct approach is to use function, like the one from docs.

    Another solution (although not that safe) is to do update with returning, check which rows were updates, and insert the rest of them

    Something along the lines of:

    update table
    set column = x.column
    from (values (1,'aa'),(2,'bb'),(3,'cc')) as x (id, column)
    where table.id = x.id
    returning id;
    

    assuming id:2 was returned:

    insert into table (id, column) values (1, 'aa'), (3, 'cc');
    

    Of course it will bail out sooner or later (in concurrent environment), as there is clear race condition in here, but usually it will work.

    Here's a longer and more comprehensive article on the topic.

提交回复
热议问题