ใช้ฟังก์ชัน REPLACE() ร่วมกับคำสั่ง UPDATE เพื่อแทนที่ตัวอักษรหรือสตริงในคอลัมน์
Syntax
UPDATE table_name SET column_name = REPLACE(column_name, 'old_string', 'new_string');
ตัวอย่าง: แทนที่ Underscore (_) ด้วยค่าว่าง (ลบออก)
1. สร้างตารางและเพิ่มข้อมูล
mysql> create table DemoTable1899 ( Code varchar(20) ); Query OK, 0 rows affected (0.00 sec)
mysql> insert into DemoTable1899 values('John_123'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1899 values('32189_Sam_987'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1899 values('Miller_David_456_909'); Query OK, 1 row affected (0.00 sec)
ข้อมูลต้นฉบับ:
mysql> select * from DemoTable1899;
+----------------------+ | Code | +----------------------+ | John_123 | | 32189_Sam_987 | | Miller_David_456_909 | +----------------------+ 3 rows in set (0.00 sec)
2. แทนที่ _ ด้วย '' (ลบ _ ทั้งหมด)
mysql> update DemoTable1899 set Code = replace(Code, '_', ''); Query OK, 3 rows affected (0.00 sec) Rows matched: 3 Changed: 3 Warnings: 0
3. ตรวจสอบผลลัพธ์
mysql> select * from DemoTable1899;
+-------------------+ | Code | +-------------------+ | John123 | | 32189Sam987 | | MillerDavid456909 | +-------------------+ 3 rows in set (0.00 sec)
REPLACE() รายละเอียด
REPLACE(str, from_str, to_str)
- แทนที่ ทุกครั้ง ที่พบ
from_strในstrด้วยto_str - Case-sensitive
- คืนค่า NULL ถ้าอะไรก็ตามเป็น NULL
ตัวอย่างเพิ่มเติม
| เป้าหมาย | SQL |
|---|---|
| แทนที่ Space ด้วย - | UPDATE t SET col = REPLACE(col, ' ', '-'); |
| ลบอักขระพิเศษทั้งหมด | UPDATE t SET col = REPLACE(REPLACE(REPLACE(col, '-', ''), '_', ''), '.', ''); |
| แทนที่หลายค่า (Nested) | REPLACE(REPLACE(col, 'a', 'b'), 'c', 'd') |
| SELECT แสดงผลแทนที่ (ไม่ UPDATE) | SELECT REPLACE(col, '_', '-') FROM table; |
Regular Expression Replace (MySQL 8.0+)
-- แทนที่ตัวเลขทั้งหมดด้วย '' SELECT REGEXP_REPLACE(col, '[0-9]+', '') FROM table;
สรุป: ใช้ UPDATE ... SET col = REPLACE(col, 'old', 'new') เพื่อแทนที่ตัวอักษรในคอลัมน์ทั้งตาราง ใช้ Nested REPLACE สำหรับหลายตัวอักษร หรือ REGEXP_REPLACE (MySQL 8+) สำหรับ Pattern ซับซ้อน