如何将子查询转换为INNER JOIN?


为了帮助大家理解,我们使用下列表格中的数据 −

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 reserve;
+------+------------+
| ID   | Day        |
+------+------------+
|    1 | 2017-12-30 |
|    2 | 2017-12-28 |
|    2 | 2017-12-25 |
|    1 | 2017-12-24 |
|    3 | 2017-12-26 |
+------+------------+
5 rows in set (0.00 sec)

这是一个子查询,将查找所有预订了汽车的客户姓名。

mysql> Select Name from customers WHERE customer_id IN (Select id from reserve);
+----------+
| Name     |
+----------+
| Rahul    |
| Yashpal  |
| Gaurav   |
+----------+
3 rows in set (0.00 sec)

利用以下步骤,我们可以将上述子查询转换为 inner join −

  • 将子查询中命名的“Reserve”表移至 FROM 子句。

  • WHERE 子句将 customer_id 列与从子查询返回的 id 进行比较。 

因此,将表达式转换为两个表的 id 列之间的显式直接比较。

mysql> SELECT Name from customers, reserve WHERE customer_id = id;
+----------+
| Name     |
+----------+
| Rahul    |
| Yashpal  |
| Yashpal  |
| Rahul    |
| Gaurav   |
+----------+
5 rows in set (0.00 sec)

正如我们所见,以上结果与子查询的结果并不完全相同,因此使用 DISTINCT 关键字可以获取以下相同结果

mysql> SELECT DISTINCT name from customers,reserve WHERE customer_id = id;
+----------+
| Name     |
+----------+
| Rahul    |
| Yashpal  |
| Gaurav   |
+----------+
3 rows in set (0.03 sec)

更新时间: 22-Jun-2020

1K+ 浏览次数

开启你的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.