14.子查询之where型子查询

本节讲解where子查询及其用法

为了大家更好的理解,我将例子中需要的sql文件上传到了百度网盘,供大家食用。
链接:https://pan.baidu.com/s/1dqQS2sQj8QoCKi3UfN1wVA 密码:h7hh

where型子查询

where型子查询:把内层查询的结果作为外层查询的结果
不太明白?举个栗子

需求:列出订购物品为TNT2的所有用户id(用户id在orders表中,订购物品在orderitems表中,其中两表用order_num来连接)
怎么办?分两个步骤:
1. 在orderitems表中查询包含TNT2的订单
2. 通过步骤1的结果来查询客户的id

mysql> # 1. 在orderitems表中查询包含TNT2的订单
mysql> select order_num from orderitems where prod_id = 'TNT2';
+-----------+
| order_num |
+-----------+
|     20005 |
|     20007 |
+-----------+
2 rows in set (0.00 sec)
mysql> # 2. 通过步骤1的结果来查询客户的id
mysql> select cust_id from orders where order_num in (20005,20007);
+---------+
| cust_id |
+---------+
|   10001 |
|   10004 |
+---------+
2 rows in set (0.18 sec)

如何执行一次MySQL语句就查询出来呢?
将两部分结合起来运用where型子查询就行啦
mysql> # where型子查询
mysql> select cust_id from orders where order_num in (
    ->  select order_num from orderitems where prod_id = 'TNT2');
+---------+
| cust_id |
+---------+
|   10001 |
|   10004 |
+---------+
2 rows in set (0.00 sec)

还是不太明白?再来看一个栗子

mysql> # where型子查询
mysql> # 通过上个例子查询得到的结果在customers表中来检索这些客户id的客户信息
mysql> select cust_name,cust_email from customers where cust_id in (
    ->  select cust_id from orders where order_num in (
    ->   select order_num from orderitems where prod_id = 'TNT2'));
+----------------+------------------+
| cust_name      | cust_email       |
+----------------+------------------+
| Coyote Inc.    | [email protected]  |
| Yosemite Place | [email protected] |
+----------------+------------------+
2 rows in set (0.15 sec)

如果想看其他有关于MySQL数据库的文章,请跳转到到MySQL自学目录

你可能感兴趣的:(MySQL自学)