您可以使用UPDATE命令在MySQL中将行值增加或减少1。语法如下-
UPDATE yourTableName set yourColumnName = yourColumnName-1 where condition;
让我们创建一个表以将行值减少1。以下是查询-
mysql> create table IncrementAndDecrementValue −> ( −> UserId int, −> UserScores int −> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into IncrementAndDecrementValue values(101,20000); mysql> insert into IncrementAndDecrementValue values(102,30000); mysql> insert into IncrementAndDecrementValue values(103,40000);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from IncrementAndDecrementValue;
以下是输出;
+--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 40000 | +--------+------------+ 3 rows in set (0.00 sec)
这是使用where条件将UserScores值减1的查询。
mysql> update IncrementAndDecrementValue set UserScores = UserScores-1 where UserId = 103; Rows matched: 1 Changed: 1 Warnings: 0
让我们检查该值是否已更新。查询如下-
mysql> select *from IncrementAndDecrementValue;
以下是显示我们已成功减小行值的输出-
+--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 39999 | +--------+------------+ 3 rows in set (0.00 sec)