Cú pháp cơ bản
SELECT * FROM table WHERE col1 = val1 AND col2 = val2 AND col3 = val3;
Tất cả điều kiện phải TRUE dòng mới được chọn.
Ví dụ minh họa
Tạo bảng sinh viên
mysql> CREATE TABLE DemoTable (
StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName VARCHAR(20),
StudentAge INT,
StudentCountryName VARCHAR(40)
);
mysql> INSERT INTO DemoTable(StudentName, StudentAge, StudentCountryName) VALUES('John', 23, 'US');
mysql> INSERT INTO DemoTable(StudentName, StudentAge, StudentCountryName) VALUES('Carol', 21, 'UK');
mysql> INSERT INTO DemoTable(StudentName, StudentAge, StudentCountryName) VALUES('John', 21, 'US');
mysql> INSERT INTO DemoTable(StudentName, StudentAge, StudentCountryName) VALUES('John', 21, 'AUS');
Dữ liệu gốc
+-----------+-------------+------------+--------------------+ | StudentId | StudentName | StudentAge | StudentCountryName | +-----------+-------------+------------+--------------------+ | 1 | John | 23 | US | | 2 | Carol | 21 | UK | | 3 | John | 21 | US | | 4 | John | 21 | AUS | +-----------+------------+------------+--------------------+
Truy vấn: John, 21 tuổi, ở AUS
mysql> SELECT * FROM DemoTable
-> WHERE StudentName = "John"
-> AND StudentAge = 21
-> AND StudentCountryName = "AUS";
Kết quả
+-----------+-------------+------------+--------------------+ | StudentId | StudentName | StudentAge | StudentCountryName | +-----------+-------------+------------+--------------------+ | 4 | John | 21 | AUS | +-----------+-------------+------------+--------------------+
Toán tử logic trong MySQL
| Toán tử | Cú pháp | Ý nghĩa |
|---|---|---|
| AND | A AND B | Cả A và B đúng |
| OR | A OR B | A đúng HOẶC B đúng |
| NOT | NOT A | Phủ định A |
| XOR | A XOR B | Chỉ một trong hai đúng |
Thứ tự ưu tiên
NOTANDOR
→ Dùng ngoặc đơn () để rõ ràng:
WHERE (A = 1 OR A = 2) AND B = 3
Tối ưu hiệu năng với Index
- Index composite:
CREATE INDEX idx_name_age_country ON DemoTable(StudentName, StudentAge, StudentCountryName) - Thứ tự cột trong index quan trọng: cột selective nhất trước
- EXPLAIN để kiểm tra index usage
Mở rộng: Dynamic WHERE (Application)
-- PHP example
$conditions = [];
$params = [];
if ($name) { $conditions[] = "StudentName = ?"; $params[] = $name; }
if ($age) { $conditions[] = "StudentAge = ?"; $params[] = $age; }
if ($country) { $conditions[] = "StudentCountryName = ?"; $params[] = $country; }
$sql = "SELECT * FROM DemoTable";
if ($conditions) $sql .= " WHERE " . implode(" AND ", $conditions);