Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL: เพิ่มค่าในคอลัมน์ INT โดยไม่ต้องรู้ค่าเดิม (UPDATE ... SET col = col + n)


คำอธิบาย

ใช้ 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 อื่นๆ

ประโยชน์

  • ลด Round-trip Network (1 Query แทน 2: Select + Update)
  • ป้องกัน Race Condition (Concurrent Update)
  • Code สั้นกว่า อ่านง่ายกว่า
Operatorตัวอย่างผลลัพธ์
+col = col + 10บวก 10
-col = col - 5ลบ 5
*col = col * 1.1เพิ่ม 10%
/col = col / 2หาร 2
%col = col % 100Modulo 100