用 MySQL 将行值减小 1?


使用 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)

更新日期: 30-Jul-2019

720 次浏览

开启你的 职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.