我們如何將子查詢轉換為 RIGHT 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 −

  • 將子查詢中命名的“Customers”表移動到 FROM 子句,並使用 RIGHT JOIN 將其加入到“Reserve”。

  • WHERE 子句將 customer_id 列與從子查詢返回的 id 進行比較。因此,將 IN 表示式轉換為 FROM 子句中兩個表的 id 列之間的顯式直接比較。

  • 在 WHERE 子句中,將輸出限制為在“Reserve”表中具有 NULL 的行。

mysql> SELECT Name from reserve RIGHT JOIN customers ON customer_id = Id WHERE Id IS NULL;
+----------+
| Name     |
+----------+
| Virender |
+----------+
1 row in set (0.00 sec)

更新於: 2020 年 6 月 22 日

149 次瀏覽

開始你的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.