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

วิธีทดสอบว่ามีเรคคอร์ดใน MySQL Subquery หรือไม่ ด้วย EXISTS


ใช้ EXISTS Operator ทดสอบว่า Subquery คืนแถวไหม ไวยากรณ์:

WHERE EXISTS (Subquery)

EXISTS (Subquery) เป็น TRUE ถ้า Subquery คืนอย่างน้อย 1 แถว มิฉะนั้น FALSE

ตัวอย่าง

ใช้ข้อมูล Customers และ Reservations:

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 Reservations;
+------+-------------+------------+
| ID   | Customer_id | Day        |
+------+-------------+------------+
|    1 |           1 | 2017-12-30 |
|    2 |           2 | 2017-12-28 |
|    3 |           2 | 2017-12-29 |
|    4 |           1 | 2017-12-25 |
|    5 |           3 | 2017-12-26 |
+------+-------------+------------+
5 rows in set (0.00 sec)

Subquery ด้วย EXISTS

mysql> Select Name from customers WHERE EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id);
+---------+
| Name    |
+---------+
| Rahul   |
| Yashpal |
| Gaurav  |
+---------+
3 rows in set (0.06 sec)

คิวรีนี้ให้ชื่อลูกค้าที่เคยจอง (มีแถวใน Reservations)