How to increment a field in MySql using "ON DUPLICATE KEY UPDATE" when inserting multiple rows?

Darm picture Darm · Jul 23, 2011 · Viewed 11k times · Source

How to increment a field in MySql using "ON DUPLICATE KEY UPDATE" when inserting multiple rows?

For one row:

INSERT INTO table 
  (a, counter_elem) 
VALUES 
  (1, 1)
ON DUPLICATE KEY UPDATE counter_elem = counter_elem+1;

For multiple rows:

INSERT INTO table 
  (a, counter_elem) 
VALUES 
  (1, 1),
  (2, 1)
ON DUPLICATE KEY UPDATE counter_elem = ?;

This doesn't work:

counter_elem = VALUES(counter_elem)+1

Answer

TMS picture TMS · Jul 23, 2011

Exactly the same way!

INSERT INTO table 
  (a, counter_elem) 
VALUES 
  (1, 1),
  (2, 1)
ON DUPLICATE KEY UPDATE counter_elem = counter_elem + 1;

There's no problem there!