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

เพิ่มตัวเลขเข้าไปในค่าปัจจุบันของคอลัมน์ใน MySQL (UPDATE ... SET col = col + n)


คำสั่งหลัก

ใช้ UPDATE ร่วมกับการอ้างอิงคอลัมน์ตัวเอง

รูปแบบคำสั่ง

UPDATE yourTableName 
SET yourColumnName = yourColumnName + yourIntegerValue 
WHERE ;

ตัวอย่างครบถ้วน

1. สร้างตารางเก็บคะแนนเกม

mysql> create table addANumberToCurrentValueDemo 
    -> ( 
    -> Game_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    -> Game_Score int 
    -> ); 
Query OK, 0 rows affected (0.67 sec)

2. เพิ่มข้อมูลคะแนน

mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(1090); 
Query OK, 1 row affected (0.30 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(204); 
Query OK, 1 row affected (0.12 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(510); 
Query OK, 1 row affected (0.14 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(7890); 
Query OK, 1 row affected (0.14 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(8999); 
Query OK, 1 row affected (0.11 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(1093859); 
Query OK, 1 row affected (0.11 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(157596); 
Query OK, 1 row affected (0.11 sec)
mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(4857567); 
Query OK, 1 row affected (0.28 sec)

3. ดูข้อมูลก่อนอัปเดต

mysql> select * from addANumberToCurrentValueDemo;
+---------+------------+
| Game_Id | Game_Score |
+---------+------------+
| 1       | 1090       |
| 2       | 204        |
| 3       | 510        |
| 4       | 7890       |
| 5       | 8999       |
| 6       | 1093859    |
| 7       | 157596     |
| 8       | 4857567    |
+---------+------------+

4. เพิ่ม 11 เข้าไปใน Game_Score ของ Game_Id = 5

mysql> update addANumberToCurrentValueDemo 
    -> set Game_Score = Game_Score + 11 
    -> where Game_Id = 5; 
Query OK, 1 row affected (0.15 sec) Rows matched: 1 Changed: 1 Warnings: 0

5. ตรวจสอบผลลัพธ์ (8999 → 9010)

mysql> select * from addANumberToCurrentValueDemo;
+---------+------------+
| Game_Id | Game_Score |
+---------+------------+
| 1       | 1090       |
| 2       | 204        |
| 3       | 510        |
| 4       | 7890       |
| 5       | 9010       |
| 6       | 1093859    |
| 7       | 157596     |
| 8       | 4857567    |
+---------+------------+

กรณีเพิ่มค่าหลายแถวพร้อมกัน

-- เพิ่ม 10 ให้ทุกแถว
UPDATE scores SET score = score + 10;

-- เพิ่มต่างกันตามเงื่อนไข
UPDATE scores 
SET score = score + CASE 
    WHEN level = 1 THEN 10
    WHEN level = 2 THEN 20
    ELSE 5
END;

การใช้งานกับ DECIMAL/FLOAT

UPDATE products SET price = price + 1.50 WHERE category = 'electronics';

ข้อควรระวัง: WHERE clause สำคัญมาก - หากไม่ใส่จะอัปเดตทุกแถวในตาราง