如何將子查詢轉換為 LEFT 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 NOT IN (Select id From reserve);
+----------+
| Name     |
+----------+
| Virender |
+----------+
1 row in set (0.00 sec)

現在,我們可以藉助以下步驟將上述子查詢轉換成 RIGHT JOIN −

  • 將子查詢中命名的“Reserve”表移動到 FROM 子句,並使用 LEFT JOIN 將其連線到“Customers”。
  • WHERE 子句將 customer_id 列與從子查詢返回的 id 進行比較。因此,將 IN 表示式轉換為 FROM 子句中兩張表的 id 列之間的直接比較。
  • 在 WHERE 子句中,將輸出限制為 “Reserve”表中為 NULL 的那些行。
mysql> SELECT Name from customers LEFT JOIN reserve ON customer_id = Id WHERE Id IS NULL;
+----------+
| Name     |
+----------+
| Virender |
+----------+
1 row in set (0.00 sec)

更新於: 2020 年 6 月 22 日

超過 1 千次瀏覽

開啟你的事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.