用 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.