您可以在UPDATE和SET命令的帮助下更新字段以将值添加到现有值。语法如下-
UPDATE yourTableName SET yourColumnName = yourColumnName+integerValueToAdd WHERE yourCondition;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table addingValueToExisting -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(30), -> GameScore int, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入记录。查询如下-
mysql> insert into addingValueToExisting(Name,GameScore) values('John',89); mysql> insert into addingValueToExisting(Name,GameScore) values('Mike',56); mysql> insert into addingValueToExisting(Name,GameScore) values('Sam',99); mysql> insert into addingValueToExisting(Name,GameScore) values('Carol',100); mysql> insert into addingValueToExisting(Name,GameScore) values('David',67); mysql> insert into addingValueToExisting(Name,GameScore) values('Bob',78);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from addingValueToExisting;
以下是输出-
+----+-------+-----------+ | Id | Name | GameScore | +----+-------+-----------+ | 1 | John | 89 | | 2 | Mike | 56 | | 3 | Sam | 99 | | 4 | Carol | 100 | | 5 | David | 67 | | 6 | Bob | 78 | +----+-------+-----------+ 6 rows in set (0.00 sec)
更新字段以将值添加到现有值。对于我们的示例,让我们通过添加10将值110更新为100。查询如下-
mysql> update addingValueToExisting set GameScore = GameScore+10 where Id = 4; Rows matched − 1 Changed − 1 Warnings − 0
检查特定记录是否已更新。查询如下-
mysql> select *from addingValueToExisting where Id = 4;
以下是输出-
+----+-------+-----------+ | Id | Name | GameScore | +----+-------+-----------+ | 4 | Carol | 110 | +----+-------+-----------+ 1 row in set (0.00 sec)
看上面的输出,值100增加10,现在是110。