如何减少MySQL中的值使其保持零以上?

您可以使用更新命令在MySQL中减少值。这样,您也可以将值限制为不小于0。

语法如下-

update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0;

为避免该值降至零以下,可以使用yourColumnName> 0。

为了理解上述语法,让我们创建一个表。查询创建表。

mysql> create table DecrementDemo
   −> (
   −> DecrementValue int
   −> );

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

mysql> insert into DecrementDemo values(15),(14),(13),(12),(11),(10);
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;
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)