如何在 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP