Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีแปลง Subquery เป็น LEFT JOIN ใน MySQL


ตัวอย่างแปลง Subquery NOT IN เป็น LEFT JOIN ใช้ตาราง customers และ reserve:

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)

Subquery เดิม (หาลูกค้าที่ไม่ได้จอง)

mysql> Select Name from customers where customer_id NOT IN (Select id From reserve);
+----------+
| Name     |
+----------+
| Virender |
+----------+
1 row in set (0.00 sec)

แปลงเป็น LEFT JOIN

  1. ย้ายตาราง reserve ไป FROM Clause ใช้ LEFT JOIN กับ customers
  2. แปลง IN Expression เป็นการเปรียบเทียบคอลัมน์โดยตรง
  3. ใน WHERE ใส่เงื่อนไข Id IS NULL (คือไม่มี Match)
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)