คำอธิบาย
ใช้ UPDATE SET column = column + value เพื่อเพิ่มค่าในคอลัมน์ตัวเลขโดยไม่ต้อง SELECT หาค่าเดิมก่อน
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentScore int );
Query OK, 0 rows affected (0.81 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable(StudentScore) values(78); Query OK, 1 row affected (0.46 sec) mysql> insert into DemoTable(StudentScore) values(89); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(StudentScore) values(67); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentScore) values(95); Query OK, 1 row affected (0.25 sec)
แสดงข้อมูลก่อนอัปเดต
mysql> select * from DemoTable;
ผลลัพธ์:
+-----------+--------------+ | StudentId | StudentScore | +-----------+--------------+ | 1 | 78 | | 2 | 89 | | 3 | 67 | | 4 | 95 | +-----------+--------------+ 4 rows in set (0.00 sec)
คิวรี่เพิ่ม 21 คะแนนให้ StudentId=3
mysql> update DemoTable set StudentScore = StudentScore + 21 where StudentId = 3; Query OK, 1 row affected (0.22 sec) Rows matched: 1 Changed: 1 Warnings: 0
ตรวจสอบข้อมูลหลังอัปเดต
mysql> select * from DemoTable;
ผลลัพธ์:
+-----------+--------------+ | StudentId | StudentScore | +-----------+--------------+ | 1 | 78 | | 2 | 89 | | 3 | 88 | | 4 | 95 | +-----------+--------------+ 4 rows in set (0.00 sec)
คำอธิบาย
- StudentScore = StudentScore + 21: ใช้ค่าปัจจุบันของคอลัมน์บวก 21
- ไม่ต้อง SELECT หาค่าเดิมมาคำนวณใน Application
- Atomic Operation: อ่าน-คำนวณ-เขียน ใน Statement เดียว (Thread-safe)
Operator อื่นๆ
| Operator | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|
| + | col = col + 10 | บวก 10 |
| - | col = col - 5 | ลบ 5 |
| * | col = col * 1.1 | เพิ่ม 10% |
| / | col = col / 2 | หาร 2 |
| % | col = col % 100 | Modulo 100 |