如何借助MySQL子查询来过滤数据?

WBOY
WBOY 转载
2023-08-30 15:45:08 221浏览

如何借助MySQL子查询来过滤数据?

通过使用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)

以上就是如何借助MySQL子查询来过滤数据?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除