Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql update a field plus 1

Tags:

sql

mysql

hi there I want update a field plus one.

for example:

if 0 -> 0+1
if 1 -> 1+1

if do it with this code:

UPDATE article SET likehits = '+1' WHERE id ='129'

for all result, the result is 1.

what's the wrong?

like image 756
samil Avatar asked Feb 06 '16 10:02

samil


People also ask

How do I increment in MySQL?

Syntax for MySQL MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.


1 Answers

likehits = '+1' will not actually add one to a field instead it will just assign literal +1 to likehits column value.

In order to add 1 try this

UPDATE article 
SET likehits = likehits + 1
WHERE id ='129'

However, it looks like likehits column is of type nvarchar, if so then try this (assuming likehits column stores only numbers)

UPDATE article 
SET likehits = CAST((CAST(likehits AS INT) + 1) AS nvarchar(64)) 
WHERE id ='129'
like image 174
tchelidze Avatar answered Sep 24 '22 09:09

tchelidze