Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 568
Darm Avatar asked Jul 23 '11 17:07

Darm


1 Answers

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!

like image 129
Tomas Avatar answered Sep 22 '22 06:09

Tomas