Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql: REPLACE INTO with number=number+1

I would like do something like this in one only query.

REPLACE INTO table ( id, number ) VALUES ( 'test', number=number+5 )

What I want is (the first time!) insert the row and set the number 5. the other times (if already exist) add 5 at the number.

Is it possible? I can't find nothing on line.


2 Answers

just be sure that ID is unique. Use INSERT ... ON DUPLICATE KEY UPDATE Syntax

INSERT INTO tableName (id, number)
VALUES ('test', 5)
ON DUPLICATE KEY UPDATE
number = number + 5
like image 134
John Woo Avatar answered Dec 06 '25 04:12

John Woo


Assuming that id is a proper key (e.g. primary key):

INSERT INTO `table` (id, number)
VALUES ('test', 5)
ON DUPLICATE KEY UPDATE number=number+VALUES(number)
like image 21
Álvaro González Avatar answered Dec 06 '25 05:12

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!