借助IN关键字,我们可以使用子查询来过滤数据。这是因为我们可以使用查询结果,就像我们使用IN运算符使用值列表根据另一个查询的结果过滤查询一样。子查询出现在IN关键字后的括号中。
我们使用下表中的数据来说明此示例-
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)
下面的查询对子查询使用“ IN”运算符,并在比较子查询返回的所有值后返回结果。
mysql> SELECT * from customers WHERE customer_id IN (Select customer_id from reservations); +-------------+----------+ | Customer_Id | Name | +-------------+----------+ | 1 | Rahul | | 2 | Yashpal | | 3 | Gaurav | +-------------+----------+ 3 rows in set (0.00 sec)