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

วิธี Nest Subquery ซ้อนใน Subquery อีกตัว (Nested Subquery) ใน MySQL


Subquery ซ้อนใน Subquery เรียกว่า Nested Subquery ตัวอย่างใช้ตาราง Cars, Customers, Reservations:

mysql> Select * from Cars;
+------+--------------+---------+
| ID   | Name         | Price   |
+------+--------------+---------+
|    1 | Nexa         |  750000 |
|    2 | Maruti Swift |  450000 |
|    3 | BMW          | 4450000 |
|    4 | VOLVO        | 2250000 |
|    5 | Alto         |  250000 |
|    6 | Skoda        | 1250000 |
|    7 | Toyota       | 2400000 |
|    8 | Ford         | 1100000 |
+------+--------------+---------+
8 rows in set (0.02 sec)

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)

Nested Subquery

mysql> Select * from Customers where customer_id IN (Select Customer_id from reservations where id = (Select id from cars WHERE name = 'BMW'));
+-------------+---------+
| Customer_Id | Name    |
+-------------+---------+
|           2 | Yashpal |
+-------------+---------+
1 row in set (0.00 sec)

ลำดับการทำงาน: Inner-most: หา ID ของ BMW (ได้ 3) -> Middle: หา Customer_id จาก Reservations ที่ id=3 (ได้ 2) -> Outer: หา Customer ที่ customer_id=2 (ได้ Yashpal)