Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การใช้ ALL, ANY, SOME, IN Operators กับ MySQL Subquery


ALL, ANY, SOME, IN เปรียบเทียบค่ากับทุกค่าที่ Subquery คืน ต้องตามหลัง Comparison Operator เสมอ

ไวยากรณ์

Operand comparison_operator ALL (subquery)
Operand comparison_operator ANY (subquery)
Operand comparison_operator SOME (subquery)
Operand comparison_operator IN (subquery)

ตัวอย่าง

ใช้ข้อมูลจาก Customers และ Reservations:

mysql> Select * from Customers;
+-------------+----------+
| Customer_Id | Name     |
+-------------+----------+
|           1 | Rahul    |
|           2 | Yashpal  |
|           3 | Gaurav   |
|           4 | Virender |
+-------------+----------+
4 rows in set (0.00 sec)

mysql> Select * from Reservations;
+------+-------------+------------+
| ID   | Customer_id | Day        |
+------+-------------+------------+
|    1 |           1 | 2017-12-30 |
|    2 |           2 | 2017-12-28 |
|    3 |           2 | 2017-12-29 |
|    4 |           1 | 2017-12-25 |
|    5 |           3 | 2017-12-26 |
+------+-------------+------------+
5 rows in set (0.00 sec)

ใช้ ALL

mysql> SELECT customer_id from Customers WHERE customer_id <> ALL(Select customer_id from reservations);
+-------------+
| customer_id |
+-------------+
|           4 |
+-------------+
1 row in set (0.00 sec)

ใช้ ANY

mysql> SELECT customer_id from customers WHERE customer_id = ANY(Select customer_id from reservations);
+-------------+
| customer_id |
+-------------+
|           1 |
|           2 |
|           3 |
+-------------+
3 rows in set (0.00 sec)

ใช้ SOME

mysql> SELECT customer_id from customers WHERE customer_id = Some(Select customer_id from reservations);
+-------------+
| customer_id |
+-------------+
|           1 |
|           2 |
|           3 |
+-------------+
3 rows in set (0.00 sec)

ใช้ IN

mysql> SELECT customer_id from customers WHERE customer_id IN (Select customer_id from reservations);
+-------------+
| customer_id |
+-------------+
|           1 |
|           2 |
|           3 |
+-------------+
3 rows in set (0.00 sec)

สรุป: ANY และ SOME ให้ผลลัพธ์เหมือน IN ส่วน ALL ต้องตรงกับทุกค่า