php 如何更新字段以将值添加到现有值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12742863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:07:47  来源:igfitidea点击:

How to update field to add value to existing value?

phpmysqlsql

提问by Jam Ville

How to update field to add value to existing value?
For example I have

如何更新字段以将值添加到现有值?
例如我有

Table name: table

表名: table

id   credit
1      4
2      5
3      3

Is there a way to simply add value to the credit?
like

有没有办法简单地为信用增加价值?
喜欢

UPDATE table SET credit = '+7' WHERE id='1' 

I want to add 7 to 4 so that the credit=11 where id='1'
How to do this?

我想将 7 添加到 4 以便 credit=11 where id='1'
如何做到这一点?

回答by MatthewMcGovern

UPDATE table SET credit = credit + 7 WHERE id = 1

回答by John Woo

This is just a simple UPDATE. Try the following.

这只是一个简单的UPDATE. 请尝试以下操作。

UPDATE tableName
SET Credit = Credit + 7
WHERE ID = 1

note that ID = 1and ID = '1'is the same as the server automatically parses it.

注意ID = 1ID = '1'服务器自动解析它是一样的。

回答by hims056

Simply use credit = credit + 7instead of credit = '+7'in UPDATEstatement

简单地使用credit = credit + 7而不是credit = '+7'UPDATE语句中

UPDATE tablename SET credit = credit + 7 WHERE id = 1

See this SQLFiddle

看到这个 SQLFiddle

回答by iLaYa ツ

Try this code

试试这个代码

UPDATE table SET credit = credit + 7 WHERE id='1' 

回答by Gopesh Sharma

Just try this...

试试这个...

UPDATE table SET credit = credit + 7 WHERE id = 1

回答by Hussain Akhtar Wahid 'Ghouri'

well '+' is an operator so u need to provide the parameter it requires. '+' operator is an binary operator thus we need to provide two parameters to it with the syntax

'+' 是一个运算符,所以你需要提供它需要的参数。'+' 运算符是一个二元运算符,因此我们需要使用语法为其提供两个参数

 value1+value2

though it may take parameters of many data types by writing '+7' you are only sending a String value "+7" replacing your previous value

虽然它可以通过写入 '+7' 来获取多种数据类型的参数,但您只会发送一个字符串值“+7”来替换您之前的值

so u better use

所以你最好用

UPDATE table SET credit = '+7' WHERE id='1'

don't confuse '+' operator with other increment operators

不要将“+”运算符与其他增量运算符混淆

回答by KisnardOnline

I wanted to add to this with an 'ON DUPLICATE KEY UPDATE' example(based on the answer by @hims056). I found this answer but needed 'ON DUP...' so I figured may as well post it here.

我想添加一个“ON DUPLICATE KEY UPDATE”示例(基于@hims056的答案)。我找到了这个答案,但需要“ON DUP...”所以我想不妨把它贴在这里。

INSERT INTO table1 
(`id`, `credit`)
VALUES (1, 4)
ON DUPLICATE KEY UPDATE
`credit` = `credit` + 7;

See the SQL Fiddle here

请参阅此处的 SQL 小提琴