คำอธิบาย
ใช้ UPDATE ... SET column = new_value WHERE condition เพื่อเปลี่ยนค่าเฉพาะแถวที่ตรงเงื่อนไข
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Score int );
Query OK, 0 rows affected (0.45 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable(Score) values(56); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable(Score) values(78); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(Score) values(34); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Score) values(55); Query OK, 1 row affected (0.37 sec)
แสดงข้อมูลก่อนอัปเดต
mysql> select * from DemoTable;
ผลลัพธ์:
+-----------+-------+ | StudentId | Score | +-----------+-------+ | 1 | 56 | | 2 | 78 | | 3 | 34 | | 4 | 55 | +-----------+-------+ 4 rows in set (0.00 sec)
คิวรี่ UPDATE แทนที่ Score ของ StudentId=3
mysql> update DemoTable set Score = 95 where StudentId = 3; Query OK, 1 row affected (0.12 sec) Rows matched: 1 Changed: 1 Warnings: 0
ตรวจสอบข้อมูลหลังอัปเดต
mysql> select * from DemoTable;
ผลลัพธ์:
+-----------+-------+ | StudentId | Score | +-----------+-------+ | 1 | 56 | | 2 | 78 | | 3 | 95 | | 4 | 55 | +-----------+-------+ 4 rows in set (0.00 sec)
คำอธิบาย
- WHERE StudentId = 3: กรองเฉพาะแถวที่ 3
- SET Score = 95: ตั้งค่าใหม่เป็น 95 (แทนที่ 34)
- Rows matched: 1, Changed: 1: พบ 1 แถว และเปลี่ยนแปลง 1 แถว
UPDATE หลายคอลัมน์พร้อมกัน
UPDATE DemoTable SET Score = 100, StudentName = 'Updated' WHERE StudentId = 1;
UPDATE ทุกแถว (ไม่มี WHERE)
UPDATE DemoTable SET Score = 0;
ระวัง: จะเปลี่ยนทุกแถวในตาราง!