การ Decrement ค่าด้วย UPDATE แบบง่าย
ใช้คำสั่ง UPDATE ตั้งค่าใหม่ = ค่าเดิม - 1 พร้อมเงื่อนไข WHERE
รูปแบบคำสั่ง
UPDATE yourTableName SET yourColumnName = yourColumnName - 1 WHERE condition;
ตัวอย่างสร้างตารางและข้อมูล
mysql> CREATE TABLE IncrementAndDecrementValue (
-> UserId INT,
-> UserScores INT
-> );
Query OK, 0 rows affected (0.60 sec)
mysql> INSERT INTO IncrementAndDecrementValue VALUES(101,20000);
mysql> INSERT INTO IncrementAndDecrementValue VALUES(102,30000);
mysql> INSERT INTO IncrementAndDecrementValue VALUES(103,40000);
ข้อมูลเริ่มต้น
mysql> SELECT * FROM IncrementAndDecrementValue;
+--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 40000 | +--------+------------+ 3 rows in set (0.00 sec)
ลดค่า UserScores ของ UserId=103 ลง 1
mysql> UPDATE IncrementAndDecrementValue
-> SET UserScores = UserScores - 1 WHERE UserId = 103;
Query OK, 1 row affected (0.41 sec)
ผลลัพธ์
mysql> SELECT * FROM IncrementAndDecrementValue;
+--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 39999 | +--------+------------+ 3 rows in set (0.00 sec)
รูปแบบอื่นที่เทียบเท่า:
-
-
-
-