สถานการณ์
คอลัมน์ StudentCode เก็บรหัสนักศึกษารูปแบบต่างๆ ต้องการค้นหาที่มี Pattern: ตัวอักษรตามด้วย Underscore และตัวเลข (เช่น 909_Sam, 3_Carol_455)
วิธีแก้: ใช้ REGEXP
WHERE column REGEXP 'pattern' ใช้ POSIX Regular Expression
ตัวอย่างการใช้งาน
1. สร้างตาราง
mysql> CREATE TABLE DemoTable1573 (
-> StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentCode VARCHAR(20)
-> );
Query OK, 0 rows affected (0.63 sec)
2. เพิ่มข้อมูล
mysql> INSERT INTO DemoTable1573(StudentCode) VALUES('STU_774');
Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO DemoTable1573(StudentCode) VALUES('909_Sam');
Query OK, 1 row affected (0.17 sec)
mysql> INSERT INTO DemoTable1573(StudentCode) VALUES('3_Carol_455');
Query OK, 1 row affected (0.11 sec)
mysql> INSERT INTO DemoTable1573(StudentCode) VALUES('David_903');
Query OK, 1 row affected (0.14 sec)
3. ค้นหาด้วย REGEXP: ตัวอักษร + _ + ตัวเลข
mysql> SELECT * FROM DemoTable1573 WHERE StudentCode REGEXP '[a-zA-Z]_[0-9]';
ผลลัพธ์:
+-----------+-------------+ | StudentId | StudentCode | +-----------+-------------+ | 2 | 909_Sam | | 3 | 3_Carol_455 | +-----------+-------------+ 2 rows in set (0.14 sec)
อธิบาย Pattern: [a-zA-Z]_[0-9]
[a-zA-Z]- ตัวอักษร 1 ตัว (อังกฤษ)_ - Underscore ตรงตัว[0-9]- ตัวเลข 1 ตัว
Regex Patterns พื้นฐาน
| Pattern | ความหมาย |
|---|---|
| ^ | เริ่มต้นสตริง |
| $ | สิ้นสุดสตริง |
| . | ตัวอักษรใดๆ 1 ตัว |
| [abc] | a หรือ b หรือ c |
| [a-z] | a ถึง z |
| [^abc] | ไม่ใช่ a,b,c |
| * | 0 หรือมากกว่า |
| + | 1 หรือมากกว่า |
| ? | 0 หรือ 1 |
| {n} | n ครั้งพอดี |
| | | OR |
MySQL 8.0+ Enhanced Regex
REGEXP_LIKE()- Function Version (Return Boolean)REGEXP_SUBSTR()- ดึงส่วนที่ MatchREGEXP_REPLACE()- แทนที่ด้วย RegexREGEXP_INSTR()- หาตำแหน่ง Match
Performance Warning
- REGEXP → Full Table Scan (ไม่ใช้ Index)
- ตารางใหญ่ ควรเพิ่ม WHERE Condition อื่น กรองก่อน
- Consider: Full-text Search, Generated Column + Index, Application-side Filter
กรณีการใช้งานจริง
- Validate Email/Phone Format
- ค้นหา Pattern ใน Log/Message
- Data Quality: หาข้อมูล Format ผิด
- Extract: ดึง Serial Number, Tracking Code จาก Text