ใช้ CONCAT() ร่วมกับ REPLACE(), LEFT(), SUBSTRING() และ INSTR() เพื่อแทนที่เฉพาะครั้งแรกที่พบ
ไวยากรณ์
UPDATE yourTableName SET YourColumn = CONCAT(
REPLACE(LEFT(YourColumn, INSTR(YourColumn, 'char_to_find')), 'char_to_find', 'replacement'),
SUBSTRING(YourColumn, INSTR(YourColumn, 'char_to_find') + 1)
);
ตัวอย่างการใช้งาน
สร้างตารางและเพิ่มข้อมูล:
mysql> create table UserInformation (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(10),
-> UserPost text
-> );
Query OK, 0 rows affected (2.05 sec)
mysql> insert into UserInformation(UserName,UserPost) values('Larry','Thks is a MySQL query');
mysql> insert into UserInformation(UserName,UserPost) values('Mike','Thks is not a java program');
mysql> insert into UserInformation(UserName,UserPost) values('Sam','Thks is a SQL syntax');
ข้อมูลเดิม (Thks = Thanks ที่พิมพ์ผิด):
+--------+----------+----------------------------+ | UserId | UserName | UserPost | +--------+----------+----------------------------+ | 1 | Larry | Thks is a MySQL query | | 2 | Mike | Thks is not a java program | | 3 | Sam | Thks is a SQL syntax | +--------+----------+----------------------------+
แทนที่ 'k' แรกด้วย 'i' (Thks → This):
mysql> update UserInformation
-> set UserPost = CONCAT(
REPLACE(LEFT(UserPost, INSTR(UserPost, 'k')), 'k', 'i'),
SUBSTRING(UserPost, INSTR(UserPost, 'k') + 1)
);
Query OK, 3 rows affected (0.16 sec)
ผลลัพธ์:
+--------+----------+----------------------------+ | UserId | UserName | UserPost | +--------+----------+----------------------------+ | 1 | Larry | This is a MySQL query | | 2 | Mike | This is not a java program | | 3 | Sam | This is a SQL syntax | +--------+----------+----------------------------+
แทนที่เฉพาะตัว 'k' ตัวแรกในแต่ละแถว