Insert, on duplicate update in PostgreSQL?

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

    I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.

    My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.

    This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.

    The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.

     #This is pseudo-code - within the application:
     BEGIN TRANSACTION - get transaction lock
     SELECT all current name value pairs where id = $id into a hash record
     create a merge record from the current and update record
      (set intersection where shared keys in new win, and empty values in new are deleted).
     DELETE all name value pairs where id = $id
     COPY/INSERT merged records 
     END TRANSACTION
    

提交回复
热议问题