在 MySQL 中将行值减少 1?

mysqlmysqli database

您可以使用 UPDATE 命令在 MySQL 中将行值增加或减少 1。语法如下 −

UPDATE yourTableName set yourColumnName = yourColumnName-1 where condition;

让我们创建一个表来将行值减少 1。以下是查询 −

mysql> create table IncrementAndDecrementValue
   −> (
   −> UserId int,
   −> UserScores int
   −> );
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下 −

mysql> insert into IncrementAndDecrementValue values(101,20000);
Query OK, 1 row affected (0.13 sec)

mysql> insert into IncrementAndDecrementValue values(102,30000);
Query OK, 1 row affected (0.20 sec)

mysql> insert into IncrementAndDecrementValue values(103,40000);
Query OK, 1 row affected (0.11 sec)

使用 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;
Query OK, 1 row affected (0.41 sec)
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)

相关文章