How to update field to add value to existing value?

前端 未结 7 1945
迷失自我
迷失自我 2021-01-03 18:11

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

Table name: table

id   credit
1      4
2      5
3      3


        
相关标签:
7条回答
  • 2021-01-03 18:53

    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

    so u better use

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

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

    0 讨论(0)
  • 2021-01-03 18:59

    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.

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

    See the SQL Fiddle here

    0 讨论(0)
  • 2021-01-03 19:02
    UPDATE table SET credit = credit + 7 WHERE id = 1
    
    0 讨论(0)
  • 2021-01-03 19:02

    Simply use credit = credit + 7 instead of credit = '+7' in UPDATE statement

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

    See this SQLFiddle

    0 讨论(0)
  • 2021-01-03 19:03

    Just try this...

    UPDATE table SET credit = credit + 7 WHERE id = 1
    
    0 讨论(0)
  • 2021-01-03 19:09

    This is just a simple UPDATE. Try the following.

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

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

    0 讨论(0)
提交回复
热议问题