INSERT … ON DUPLICATE KEY UPDATE with WHERE?

后端 未结 6 2057
慢半拍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 01:54

    This is our final solution, works like a charm!

    The insert ignore will make sure that the row exists on both the master and slave, in case they've ever diverted.

    The update ... where makes sure that only the most recent update, globally, is the end result after all replication is done.

    mysql> desc test;
    +-------+--------------+------+-----+-------------------+-------+
    | Field | Type         | Null | Key | Default           | Extra |
    +-------+--------------+------+-----+-------------------+-------+
    | id    | int(11)      | NO   | PRI | NULL              |       | 
    | value | varchar(255) | YES  |     | NULL              |       | 
    | ts    | timestamp    | NO   |     | CURRENT_TIMESTAMP |       | 
    +-------+--------------+------+-----+-------------------+-------+
    
    mysql> insert ignore into test values (4, "foo", now());    
    mysql> update test set value = "foo", ts = now() where id = 4 and ts <= now();
    

提交回复
热议问题