Thay vì chạy nhiều SELECT riêng lẻ, gom chung bằng IN(). Tạo bảng:
mysql> CREATE TABLE DemoTable (
Id INT,
Name VARCHAR(100),
Age INT
); Query OK, 0 rows affected (0.77 sec)
Chèn dữ liệu:
mysql> INSERT INTO DemoTable VALUES(1,'Chris',23); Query OK, 1 row affected (0.39 sec) mysql> INSERT INTO DemoTable VALUES(2,'David',21); Query OK, 1 row affected (0.56 sec) mysql> INSERT INTO DemoTable VALUES(3,'Mike',24); Query OK, 1 row affected (0.28 sec) mysql> INSERT INTO DemoTable VALUES(4,'Robert',22); Query OK, 1 row affected (0.12 sec)
Hiển thị dữ liệu:
mysql> SELECT * FROM DemoTable;
Kết quả:
+------+--------+------+ | Id | Name | Age | +------+--------+------+ | 1 | Chris | 23 | | 2 | David | 21 | | 3 | Mike | 24 | | 4 | Robert | 22 | +------+--------+------+ 4 rows in set (0.00 sec)
Thay vì 3 truy vấn riêng cho Age=21,22,23, dùng một truy vấn:
mysql> SELECT Name FROM DemoTable WHERE Age IN(21,22,23);
Kết quả:
+--------+ | Name | +--------+ | Chris | | David | | Robert | +--------+ 3 rows in set (0.00 sec)
Lợi ích: Giảm round-trip đến database, tận dụng index trên cột Age (nếu có).