MySQL 如何递减一个值并保证它在零以上
您可以使用update命令在MySQL中递减值。使用此命令,您也可以限制该值不低于0。
语法如下―
update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0;
为了避免值低于零,您可以使用yourColumnName > 0。
为了理解上述语法,让我们创建一个表。创建表的查询如下。
mysql> create table DecrementDemo
−> (
−> DecrementValue int
−> );
Query OK, 0 rows affected (0.62 sec)
使用insert语句在表中插入一些记录。查询如下―
mysql> insert into DecrementDemo values(15),(14),(13),(12),(11),(10);
Query OK, 6 rows affected (0.18 sec)
Records: 6 Duplicates: 0 Warnings: 0
现在,您可以使用select语句从表中显示所有记录。查询如下―
mysql> select *from DecrementDemo;
输出如下―
+----------------+
| DecrementValue |
+----------------+
| 15 |
| 14 |
| 13 |
| 12 |
| 11 |
| 10 |
+----------------+
6 rows in set (0.00 sec)
下面是从表中递减值的查询语句―
mysql> update DecrementDemo
−> set DecrementValue = DecrementValue - 1 where DecrementValue > 0;
Query OK, 6 rows affected (0.16 sec)
Rows matched: 6 Changed: 6 Warnings: 0
使用以下查询检查递减值是否有效―
mysql> select *from DecrementDemo;
输出如下―
+----------------+
| DecrementValue |
+----------------+
| 14 |
| 13 |
| 12 |
| 11 |
| 10 |
| 9 |
+----------------+
6 rows in set (0.00 sec)
阅读更多:MySQL 教程