Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL Escape % Character ใน LIKE Pattern (Left/Middle Position)

Escape Wildcard % และ _ ใน LIKE Pattern

ใน LIKE Pattern: % = 0 หรือมากกว่า ตัวอักษร, _ = ตัวอักษร 1 ตัว ต้อง Escape ด้วย Backslash (\) ถ้าต้องการ Match ตัวอักษรจริง

ตัวอย่าง: ค้นหาสตริงที่ลงท้ายด้วย %

CREATE TABLE DemoTable629 (
    StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    StudentSubject TEXT
);

INSERT INTO DemoTable629(StudentSubject) VALUES
('MySQL%'), ('Spring%Hibernate'), ('%Java');

Query: หาที่ลงท้าย % (Escape ด้วย \%)

SELECT * FROM DemoTable629 
WHERE StudentSubject LIKE '%\%';

ผลลัพธ์: MySQL% เท่านั้น

+-----------+----------------+
| StudentId | StudentSubject |
+-----------+----------------+
| 1         | MySQL%         |
+-----------+----------------+

Escape Character Options

PatternMatchคำอธิบาย
LIKE '%\%'ลงท้าย %Escape % ด้วย \
LIKE '\%%'ขึ้นต้น %Escape % ตัวแรก
LIKE '%\_%'มี _ อยู่กลางEscape _ ด้วย \
LIKE '%\\%'มี \ อยู่กลางEscape \ เอง (Double Backslash)

Custom Escape Character

-- ใช้ ESCAPE clause กำหนด Escape Char เอง
SELECT * FROM DemoTable629 
WHERE StudentSubject LIKE '%|%' ESCAPE '|';
-- ตอนนี้ | เป็น Escape Char: |% = literal %, || = literal |

ข้อควรระวัง: String Literal Escape ใน SQL

ใน SQL String Literal Backslash ต้อง Double Escape:

-- ใน Query ตรงๆ
WHERE col LIKE '%\%'        -- OK: \% ใน Pattern

-- ใน Prepared Statement / Application Code
WHERE col LIKE '%\\%'       -- ต้อง Double Escape สำหรับ String Literal

Performance: LIKE เริ่มต้นด้วย % (Leading Wildcard)

  • LIKE '%text%' - ไม่ใช้ Index (Full Scan)
  • LIKE 'text%' - ใช้ Index ได้ (Prefix Match)
  • LIKE '%text' - ไม่ใช้ Index (Suffix Match)

Alternative: Fulltext Search (สำหรับ Text Search จริง)

ALTER TABLE DemoTable629 ADD FULLTEXT(StudentSubject);

SELECT * FROM DemoTable629 
WHERE MATCH(StudentSubject) AGAINST('MySQL' IN BOOLEAN MODE);

REGEXP Alternative (MySQL 8.0+)

-- Escape ใน Regex: \% = literal %
WHERE StudentSubject REGEXP 'MySQL\\%$';  -- ลงท้าย MySQL%

-- หรือใช้ Character Class
WHERE StudentSubject REGEXP 'MySQL[%]$';