ฟังก์ชัน REGEXP_REPLACE()
MySQL 8.0+ รองรับ REGEXP_REPLACE() ที่สามารถระบุได้ว่าจะแทนที่ครั้งที่เท่าไหร่ ไวยากรณ์:
REGEXP_REPLACE(expr, pattern, replacement, position, occurrence, match_type)
position: เริ่มค้นหาตำแหน่งที่ (เริ่มต้น 1)occurrence: ครั้งที่จะแทนที่ (0 = ทุกครั้ง, 1 = ครั้งแรก, 2 = ครั้งที่สอง...)
ตัวอย่าง: แทนที่คำว่า "first" ครั้งแรกเป็น "second"
ข้อความต้นฉบับ:
"This is my first MySQL query. This is the first tutorial. I am learning for the first time."
ผลลัพธ์ที่ต้องการ:
"This is my second MySQL query. This is the first tutorial. I am learning for the first time."
ขั้นตอนการทำงาน
CREATE TABLE demo26 (value TEXT);
INSERT INTO demo26 VALUES
('This is my first MySQL query. This is the first tutorial. I am learning for the first time.');
UPDATE demo26
SET value = REGEXP_REPLACE(value, 'first', 'second', 1, 1);
ผลลัพธ์หลัง UPDATE
+----------------------------------------------------------------------------------------------+ | value | +----------------------------------------------------------------------------------------------+ | This is my second MySQL query. This is the first tutorial. I am learning for the first time. | +----------------------------------------------------------------------------------------------+
พารามิเตอร์สำคัญ
| พารามิเตอร์ | ค่า | ความหมาย |
|---|---|---|
| pattern | 'first' | รูปแบบที่ต้องการค้นหา (รองรับ regex) |
| replacement | 'second' | ข้อความที่จะแทนที่ |
| position | 1 | เริ่มค้นหาตัวแรกของสตริง |
| occurrence | 1 | แทนที่ครั้งแรกที่พบเท่านั้น |
กรณีศึกษาเพิ่มเติม
แทนที่ครั้งที่ 2
REGEXP_REPLACE(value, 'first', 'second', 1, 2)
แทนที่ทั้งหมด (ค่าเริ่มต้น)
REGEXP_REPLACE(value, 'first', 'second') -- occurrence = 0
ไม่สนใจตัวพิมพ์เล็ก-ใหญ่
REGEXP_REPLACE(value, 'first', 'second', 1, 1, 'i')
หมายเหตุ
- ต้องใช้ MySQL 8.0 ขึ้นไป
- สำหรับ MySQL 5.7 หรือ MariaDB ให้ใช้
REPLACE()ร่วมกับ logic อื่น (ซับซ้อนกว่า) - REGEXP_REPLACE คืนค่า string ใหม่ ไม่เปลี่ยนข้อมูลต้นฉบับจนกว่าจะ UPDATE