如何將子查詢轉換成左連線?
為了使文章易於理解,我們使用了以下表格中的資料 −
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)
現在,按照以下步驟,我們可以將上述子查詢轉換成右連線 −
- 將子查詢中命名的“Reserve”表移動到 FROM 子句,並使用左連線將其連線到“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)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP