ใช้ Regular Expression ใน WHERE ... REGEXP เพื่อค้นหาข้อมูลที่ตรงกับหลายรูปแบบพร้อมกัน
สร้างตารางและเพิ่มข้อมูล
mysql> CREATE TABLE DemoTable (
ProductId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
ProductName VARCHAR(20)
);
mysql> INSERT INTO DemoTable(ProductName) VALUES
('Product-1'), ('Product2'), ('Product1'), ('Product-3'),
('Product3'), ('Product-4'), ('Product4');
ดูข้อมูล
mysql> SELECT * FROM DemoTable;
+-----------+-------------+
| ProductId | ProductName |
+-----------+-------------+
| 1 | Product-1 |
| 2 | Product2 |
| 3 | Product1 |
| 4 | Product-3 |
| 5 | Product3 |
| 6 | Product-4 |
| 7 | Product4 |
+-----------+-------------+
ค้นหา Product ตามด้วย 1,2,3,4 (มี - หรือไม่มีก็ได้)
mysql> SELECT * FROM DemoTable
-> WHERE ProductName REGEXP 'Product[1234].*';
ผลลัพธ์
+-----------+-------------+
| ProductId | ProductName |
+-----------+-------------+
| 2 | Product2 |
| 3 | Product1 |
| 5 | Product3 |
| 7 | Product4 |
+-----------+-------------+
คำอธิบาย Regex:
Product— ตรงตัว[1234]— ตัวอักษรใดตัวหนึ่งในชุด 1,2,3,4.*— ตามด้วยอะไรก็ได้ (รวมถึงไม่มีอะไร)
จับได้: Product1, Product2, Product3, Product4, Product-1, Product-2 ฯลฯ