我们如何将子查询转换为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)

现在,借助以下步骤,我们可以将上述子查询转换为内部联接-

  • 将子查询中命名的“保留”表移至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)