什么是MySQL子查询中的EXIST和EXIST NOT运算符的用途?
EXIST运算符用于测试子查询结果集中的行是否存在。如果找到子查询行值,则EXISTS子查询为TRUE,NOT EXISTS子查询为FALSE。为说明此问题,我们使用以下数据的表Cars,Customers和Reservations-
mysql> Select * from Cars;
+------+--------------+---------+
| ID | Name | Price |
+------+--------------+---------+
| 1 | Nexa | 750000 |
| 2 | Maruti Swift | 450000 |
| 3 | BMW | 4450000 |
| 4 | VOLVO | 2250000 |
| 5 | Alto | 250000 |
| 6 | Skoda | 1250000 |
| 7 | Toyota | 2400000 |
| 8 | Ford | 1100000 |
+------+--------------+---------+
8 rows in set (0.02 sec)
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)
以下是使用上述表的MySQL子查询与EXIST的示例-
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)
上面的查询列出了进行了预订的客户的姓名。
以下是使用上述表的MySQL子查询与NOT EXIST的示例-
mysql> Select Name from customers WHERE NOT EXISTS (SELECT * FROM Reservations WHERE Customers.customer_id = Reservations.customer_id);
+----------+
| Name |
+----------+
| Virender |
+----------+
1 row in set (0.04 sec)
上面的查询列出了没有进行任何预订的客户的姓名。
阅读更多:MySQL 教程
极客教程