MySQL's Efficient Upsert: INSERT ... ON DUPLICATE KEY UPDATE
MySQL frequently faces scenarios requiring either inserting a new row or updating an existing one based on a key's presence. This combined operation, known as an upsert (or merge), is elegantly handled in MySQL using a single statement.
Leveraging INSERT ... ON DUPLICATE KEY UPDATE
Instead of multiple queries, MySQL's INSERT ... ON DUPLICATE KEY UPDATE
statement streamlines this process. Its syntax is straightforward:
<code class="language-sql">INSERT INTO `table_name` (`column1`, `column2`, ...) VALUES (`value1`, `value2`, ...) ON DUPLICATE KEY UPDATE `column1` = `value1`, `column2` = `value2`, ...</code>
Practical Application: Incrementing Usage Counts
Imagine a usage
table with columns thing_id
, times_used
, and first_time_used
. The goal is to increase times_used
for a given thing_id
if the row exists; otherwise, insert a new row.
This task is easily accomplished using INSERT ... ON DUPLICATE KEY UPDATE
:
<code class="language-sql">INSERT INTO `usage` (`thing_id`, `times_used`, `first_time_used`) VALUES (4815162342, 1, NOW()) ON DUPLICATE KEY UPDATE `times_used` = `times_used` + 1</code>
This query intelligently handles both scenarios: if thing_id
4815162342 exists, times_used
is incremented; otherwise, a new row is added with the specified values. This demonstrates the efficiency and conciseness of MySQL's upsert functionality.
The above is the detailed content of How Can MySQL's INSERT ... ON DUPLICATE KEY UPDATE Efficiently Handle Inserts and Updates?. For more information, please follow other related articles on the PHP Chinese website!