如何使用包含对外部查询中出现的表的引用的子查询?

mysqlmysqli database更新于 2024/3/8 15:56:00

包含对外部查询中出现的表的引用的子查询称为相关子查询。在这种情况下,MySQL 从内部查询评估外部查询。为了理解它,我们从表"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)

以下是两个 MySQL 查询,它们的子查询包含对表(即也出现在外部查询中的‘Cars’)的引用。

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 AVG(Price) from Cars",然后评估外部查询"Select Name from Cars Where Price"。类似地,MySQL 在下面查询中进行评估。

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

相关文章