INSERT … ON DUPLICATE KEY UPDATE with WHERE?

后端 未结 6 2082
慢半拍i
慢半拍i 2020-11-29 01:26

I\'m doing a INSERT ... ON DUPLICATE KEY UPDATE but I need the update part to be conditional, only doing the update if some extra condition has changed.

6条回答
  •  借酒劲吻你
    2020-11-29 02:08

    On duplicate key do not allow us to use where clause, so there are two alternative to achieve the same.

    1. If you know most of the time you will get the duplicate key then

      a. Update the table first using update query and where clause b. If update fails then insert the record into table using insert query

    2. If you know most of the time you are going to insert into table then

      a. Insert the record into table using insert ignore query - what it does is actually ignore the insert if duplicate key found b. If insert ignore fails then update the record using update query

    For reference of insert ignore click here

提交回复
热议问题