คำสั่งหลัก
ใช้ CONCAT() ร่วมกับ UPDATE เพื่อต่อข้อความเพิ่มเข้าไปในค่าที่มีอยู่แล้ว
รูปแบบคำสั่ง
UPDATE yourTableName SET yourColumnName = CONCAT(yourColumnName, 'text_to_append') WHERE condition;
ตัวอย่างครบถ้วน
1. สร้างตารางอาจารย์และวิชา
mysql> create table addToExistingValueDemo
-> (
-> Instructor_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Instructor_Name varchar(30),
-> Instructor_TechnicalSubject text
-> );
Query OK, 0 rows affected (0.54 sec)
2. เพิ่มข้อมูล
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('John','C,C++');
Query OK, 1 row affected (0.15 sec)
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('Carol','Java,Python');
Query OK, 1 row affected (0.18 sec)
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('Bob','MySQL,SQL Server');
Query OK, 1 row affected (0.15 sec)
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('David','DataStructure');
Query OK, 1 row affected (0.18 sec)
3. ดูข้อมูลก่อนอัปเดต
mysql> select * from addToExistingValueDemo;
+---------------+-----------------+-----------------------------+ | Instructor_Id | Instructor_Name | Instructor_TechnicalSubject | +---------------+-----------------+-----------------------------+ | 1 | John | C,C++ | | 2 | Carol | Java,Python | | 3 | Bob | MySQL,SQL Server | | 4 | David | DataStructure | +---------------+-----------------+-----------------------------+
4. เพิ่มข้อความ ", Introduction To Algorithm" ให้ David (Id=4)
mysql> update addToExistingValueDemo
-> set Instructor_TechnicalSubject = concat(Instructor_TechnicalSubject, ', Introduction To Algorithm')
-> where Instructor_Id = 4;
Query OK, 1 row affected (0.10 sec) Rows matched: 1 Changed: 1 Warnings: 0
5. ตรวจสอบผลลัพธ์
mysql> select * from addToExistingValueDemo;
+---------------+-----------------+------------------------------------------+ | Instructor_Id | Instructor_Name | Instructor_TechnicalSubject | +---------------+-----------------+------------------------------------------+ | 1 | John | C,C++ | | 2 | Carol | Java,Python | | 3 | Bob | MySQL,SQL Server | | 4 | David | DataStructure, Introduction To Algorithm | +---------------+-----------------+------------------------------------------+
เคล็ดลับเพิ่มเติม
เพิ่มข้อความด้านหน้า (Prepend)
UPDATE table SET col = CONCAT('Prefix: ', col) WHERE id = 1;
เพิ่มทั้งหน้าและหลัง
UPDATE table SET col = CONCAT('[', col, ']') WHERE id = 1;
ใช้ CONCAT_WS (with separator) - จัดการ NULL อัตโนมัติ
UPDATE table SET tags = CONCAT_WS(',', tags, 'new_tag') WHERE id = 1;
ถ้า tags เป็น NULL จะได้แค่ 'new_tag' (ไม่มีคอมมานำหน้า)
ป้องกัน duplicate ตอนเพิ่ม tag
UPDATE table
SET tags = CASE
WHEN FIND_IN_SET('new_tag', tags) = 0 THEN CONCAT_WS(',', tags, 'new_tag')
ELSE tags
END
WHERE id = 1;
หมายเหตุ: CONCAT จะคืนค่า NULL หาก argument ใดเป็น NULL - ใช้ CONCAT_WS หรือ COALESCE ป้องกันได้