How do I update if exists, insert if not (AKA “upsert” or “merge”) in MySQL?

后端 未结 2 1980
挽巷
挽巷 2020-11-22 01:56

Is there an easy way to INSERT a row when it does not exist, or to UPDATE if it exists, using one MySQL query?

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 02:30

    Use INSERT ... ON DUPLICATE KEY UPDATE. For example:

    INSERT INTO `usage`
    (`thing_id`, `times_used`, `first_time_used`)
    VALUES
    (4815162342, 1, NOW())
    ON DUPLICATE KEY UPDATE
    `times_used` = `times_used` + 1
    

提交回复
热议问题