รวมเงื่อนไขหลายอย่างด้วย AND ใน WHERE
ใช้ AND เชื่อมเงื่อนไขหลายอย่างใน WHERE ทุกเงื่อนไขต้องเป็นจริง (TRUE) พร้อมกัน纔จะเลือกแถวนั้น
ตัวอย่างสร้างตารางและข้อมูล
CREATE TABLE DemoTable (
StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName VARCHAR(20),
StudentAge INT,
StudentCountryName VARCHAR(40)
);
INSERT INTO DemoTable (StudentName, StudentAge, StudentCountryName) VALUES
('John', 23, 'US'), ('Carol', 21, 'UK'), ('John', 21, 'US'), ('John', 21, 'AUS');
ข้อมูลในตาราง
+-----------+-------------+------------+--------------------+ | StudentId | StudentName | StudentAge | StudentCountryName | +-----------+-------------+------------+--------------------+ | 1 | John | 23 | US | | 2 | Carol | 21 | UK | | 3 | John | 21 | US | | 4 | John | 21 | AUS | +-----------+------------+------------+--------------------+
คำสั่งค้นหา: ชื่อ John, อายุ 21, ประเทศ AUS (ต้องตรงทั้ง 3)
SELECT * FROM DemoTable WHERE StudentName = 'John' AND StudentAge = 21 AND StudentCountryName = 'AUS';
ผลลัพธ์
+-----------+-------------+------------+--------------------+ | StudentId | StudentName | StudentAge | StudentCountryName | +-----------+-------------+------------+--------------------+ | 4 | John | 21 | AUS | +-----------+-------------+------------+--------------------+
คำอธิบาย: เงื่อนไข 3 ข้อ ต้องเป็นจริงพร้อมกัน จึงได้แถวเดียว (Id=4)
เคล็ดลับประสิทธิภาพ:
- วางเงื่อนไขที่ "เลือกได้น้อยที่สุด" (Most Selective) ไว้หน้าสุด เพื่อให้ Optimizer ตัดแถวออกได้เร็ว
- สร้าง Composite Index ครอบคอลัมน์ที่ WHERE บ่อย:
INDEX idx_name_age_country (StudentName, StudentAge, StudentCountryName) - ใช้
EXPLAINตรวจสอบ Execution Plan
ตัวดำเนินการตรรกะอื่นๆ: OR (ใดๆ หนึ่งจริง), NOT (ยกเว้น), XOR (ใดด้านหนึ่งจริงอย่างเดียว)