รวมหลายเงื่อนไข LIKE ใน WHERE Clause เดียว
ใช้ Parentheses จัดกลุ่มเงื่อนไข OR/AND ร่วมกับ LIKE ได้หลายคอลัมน์ พร้อมใช้ Wildcard % และ _
สร้างตารางและข้อมูล
mysql> CREATE TABLE DemoTable1534 (
-> ClientId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ClientName VARCHAR(20),
-> ClientAge INT,
-> ClientCountryName VARCHAR(20)
-> );
Query OK, 0 rows affected (0.78 sec)
mysql> INSERT INTO DemoTable1534(ClientName, ClientAge, ClientCountryName) VALUES
-> ('Chris Brown', 29, 'AUS'),
-> ('David Miller', 49, 'UK'),
-> ('John Doe', 43, 'US'),
-> ('Adam Smith', 38, 'US'),
-> ('Carol Taylor', 36, 'UK');
Query OK, 5 rows affected
ข้อมูลทั้งหมด
+----------+--------------+-----------+-------------------+ | ClientId | ClientName | ClientAge | ClientCountryName | +----------+--------------+-----------+-------------------+ | 1 | Chris Brown | 29 | AUS | | 2 | David Miller | 49 | UK | | 3 | John Doe | 43 | US | | 4 | Adam Smith | 38 | US | | 5 | Carol Taylor | 36 | UK | +----------+--------------+-----------+-------------------+
คำสั่ง: Multiple LIKE Conditions
mysql> SELECT * FROM DemoTable1534
-> WHERE ClientName LIKE ('%Doe%' OR ClientAge LIKE '%38%')
-> OR (ClientCountryName LIKE '%S');
Query OK, 3 rows affected (0.00 sec)
ผลลัพธ์ (พร้อม Warning: 5 warnings)
+----------+-------------+-----------+-------------------+ | ClientId | ClientName | ClientAge | ClientCountryName | +----------+-------------+-----------+-------------------+ | 1 | Chris Brown | 29 | AUS | | 3 | John Doe | 43 | US | | 4 | Adam Smith | 38 | US | +----------+-------------+-----------+-------------------+
คำอธิบายเงื่อนไข
ClientName LIKE '%Doe%'→ Match: John DoeClientAge LIKE '%38%'→ Match: Adam Smith (Age 38)ClientCountryName LIKE '%S'→ Match: AUS, US (ลงท้าย S) → Chris Brown, John Doe, Adam Smith- รวมด้วย OR → ได้ 3 แถว (Chris Brown, John Doe, Adam Smith)
⚠️ Warning: Implicit Conversion (Integer LIKE String)
ClientAge LIKE '%38%' → ClientAge เป็น INT MySQL แปลงเป็น String อัตโนมัติ (Implicit Cast) → เกิด Warning
แก้ไข: ใช้ CAST(ClientAge AS CHAR) LIKE '%38%' หรือ ClientAge = 38 (ถ้าต้องการเท่ากันพอดี)
Best Practice: ใช้ Parentheses จัดกลุ่มชัดเจน
WHERE
(ClientName LIKE '%Doe%' OR ClientName LIKE '%Smith%')
AND (ClientCountryName LIKE '%US%' OR ClientCountryName LIKE '%UK%')
AND ClientAge BETWEEN 20 AND 50
Full-Text Search Alternative (สำหรับข้อความยาว/หลายคอลัมน์)
ALTER TABLE DemoTable1534 ADD FULLTEXT(ClientName, ClientCountryName);
SELECT * FROM DemoTable1534
WHERE MATCH(ClientName, ClientCountryName) AGAINST('+Doe +US' IN BOOLEAN MODE);