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

การใช้ Subquery ที่อ้างอิงตารางซ้ำกับ Outer Query (Correlated Subquery)


Subquery ที่อ้างอิงตารางที่ปรากฏใน Outer Query เรียกว่า Correlated Subquery MySQL ประเมินจาก Inner Query ไป Outer Query ใช้ข้อมูลจากตาราง cars:

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)

ตัวอย่าง Correlated Subquery

mysql> Select Name from cars WHERE Price < (SELECT AVG(Price) from Cars);
+--------------+
| Name         |
+--------------+
| Nexa         |
| Maruti Swift |
| Alto         |
| Skoda        |
| Ford         |
+--------------+
5 rows in set (0.00 sec)

mysql> Select Name from cars WHERE Price > (SELECT AVG(Price) from Cars);
+--------+
| Name   |
+--------+
| BMW    |
| VOLVO  |
| Toyota |
+--------+
3 rows in set (0.00 sec)

คำอธิบาย: Inner Query SELECT AVG(Price) from Cars รันก่อน คืนค่าเฉลี่ย แล้ว Outer Query เปรียบเทียบ Price กับค่าเฉลี่ยนั้น