mysql更新字段加1

时间:2021-07-12 17:03:37

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.

对于所有结果,结果是1。

what's the wrong?

怎么了?

1 个解决方案

#1


1  

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

likehits ='+ 1'实际上不会向字段添加一个,而只是将字面值+1分配给likehits列值。

In order to add 1 try this

为了添加1尝试这个

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)

但是,看起来likehits列的类型为nvarchar,如果是,那么试试这个(假设likehits列只存储数字)

UPDATE article 
SET likehits = CAST((CAST(likehits AS INT) + 1) AS nvarchar(64)) 
WHERE id ='129'

#1


1  

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

likehits ='+ 1'实际上不会向字段添加一个,而只是将字面值+1分配给likehits列值。

In order to add 1 try this

为了添加1尝试这个

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)

但是,看起来likehits列的类型为nvarchar,如果是,那么试试这个(假设likehits列只存储数字)

UPDATE article 
SET likehits = CAST((CAST(likehits AS INT) + 1) AS nvarchar(64)) 
WHERE id ='129'