คำอธิบาย
ใช้ AND และ OR ร่วมกันใน WHERE clause พร้อมวงเล็บ () กำหนดลำดับความสำคัญ (Precedence)
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(40),
StudentMathMarks int,
StudentMySQLMarks int,
status ENUM('ACTIVE','INACTIVE') );
Query OK, 0 rows affected (0.47 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable(StudentName, StudentMathMarks, StudentMySQLMarks, status) values('Chris', 45, 67, 'active');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentName, StudentMathMarks, StudentMySQLMarks, status) values('Bob', 89, 78, 'inactive');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentName, StudentMathMarks, StudentMySQLMarks, status) values('David', 56, 68, 'active');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName, StudentMathMarks, StudentMySQLMarks, status) values('Robert', 68, 75, 'active');
Query OK, 1 row affected (0.18 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from DemoTable;
ผลลัพธ์:
+-----------+-------------+------------------+-------------------+----------+ | StudentId | StudentName | StudentMathMarks | StudentMySQLMarks | status | +-----------+-------------+------------------+-------------------+----------+ | 1 | Chris | 45 | 67 | ACTIVE | | 2 | Bob | 89 | 78 | INACTIVE | | 3 | David | 56 | 68 | ACTIVE | | 4 | Robert | 68 | 75 | ACTIVE | +-----------+-------------+------------------+-------------------+----------+ 4 rows in set (0.00 sec)
คิวรี่ AND OR พร้อมวงเล็บ
mysql> select * from DemoTable where status = 'active' and (StudentMathMarks = 68 or StudentMySQLMarks = 67);
ผลลัพธ์
+-----------+-------------+------------------+-------------------+--------+ | StudentId | StudentName | StudentMathMarks | StudentMySQLMarks | status | +-----------+-------------+------------------+-------------------+--------+ | 1 | Chris | 45 | 67 | ACTIVE | | 4 | Robert | 68 | 75 | ACTIVE | +-----------+-------------+------------------+-------------------+--------+ 2 rows in set (0.00 sec)
คำอธิบายลำดับความสำคัญ (Precedence)
- AND มี Precedence สูงกว่า OR
- ไม่มีวงเล็บ:
A AND B OR C=(A AND B) OR C - มีวงเล็บ:
A AND (B OR C)= A ต้อง True และ (B หรือ C ต้อง True)
ตัวอย่างในคิวรี่
status='active' AND (Math=68 OR MySQL=67)
- Chris: Active ✓, Math=45✗, MySQL=67✓ → (✗ OR ✓) = ✓ → ผ่าน
- Bob: Inactive ✗ → ตัดออก (AND ต้อง True ทั้งคู่)
- David: Active ✓, Math=56✗, MySQL=68✗ → (✗ OR ✗) = ✗ → ตัดออก
- Robert: Active ✓, Math=68✓, MySQL=75✗ → (✓ OR ✗) = ✓ → ผ่าน
แนวทางปฏิบัติที่ดี
ใช้วงเล็บเสมอ แม้จะไม่จำเป็น เพื่อความชัดเจนและป้องกัน Bug