如何将 +1 添加到现有的 MySQL 值?

让我们看一个例子并先创建一个表。

mysql> create table Add1ToExistingValue
   -> (
   -> Value int
   -> );

使用插入命令在表中插入一些记录。

查询如下

mysql> insert into Add1ToExistingValue values(10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into Add1ToExistingValue values(13);
Query OK, 1 row affected (0.15 sec)
mysql> insert into Add1ToExistingValue values(15);
Query OK, 1 row affected (0.13 sec)
mysql> insert into Add1ToExistingValue values(16);
Query OK, 1 row affected (0.14 sec)
mysql> insert into Add1ToExistingValue values(20);
Query OK, 1 row affected (0.16 sec)
mysql> insert into Add1ToExistingValue values(40);
Query OK, 1 row affected (0.15 sec)
mysql> insert into Add1ToExistingValue values(50);
Query OK, 1 row affected (0.11 sec)
mysql> insert into Add1ToExistingValue values(55);
Query OK, 1 row affected (0.17 sec)
mysql> insert into Add1ToExistingValue values(56);
Query OK, 1 row affected (0.17 sec)

使用 select 语句显示表中的所有记录。

查询如下

mysql> select *from Add1ToExistingValue;

以下是输出

+-------+
| Value |
+-------+
| 10    |
| 13    |
| 15    |
| 16    |
| 20    |
| 40    |
| 50    |
| 55    |
| 56    |
+-------+
9 rows in set (0.00 sec)

这是将 +1 添加到现有值的查询

mysql> update Add1ToExistingValue set Value=Value+1 where Value >=20;
Rows matched: 5 Changed: 5 Warnings: 0

让我们使用 select 语句检查表中的表记录。

查询如下

mysql> select *from Add1ToExistingValue;

以下是输出

+-------+
| Value |
+-------+
| 10    |
| 13    |
| 15    |
| 16    |
| 21    |
| 41    |
| 51    |
| 56    |
| 57    |
+-------+
9 rows in set (0.00 sec)