MySQL子查询

什么是子查询

子查询(subquery):子查询即嵌套在其他查询中的查询
用来在多个表中查询过滤信息。

利用子查询进行过滤

案例:
现有表customers, orders, orderitems
customers储存客户信息:
在这里插入图片描述
orders储存订单信息:
在这里插入图片描述
orderitems储存订单与货物的详细信息:
在这里插入图片描述
现在需要查询订购TCNT2的所有客户应该怎样检索?
传统查询:

  1. 查询TNCT2的订单编号order_num
select order_num from orderitems where prod_id = 'TNT2';

+-----------+ 
| order_num | 
+-----------+ 
|     20005 | 
|     20007 | 
+-----------+ 
 
  1. 通过订单编号order_num查询对应的客户编号cust_id
select cust_id from orders where order_num IN (20005,20007);

+---------+
| cust_id | 
+---------+ 
|   10001 | 
|   10004 | 
+---------+ 
  1. 检索前一步骤返回所有客户id的客户信息
 select cust_name,cust_contact from customers where cust_id in (10001,10004); 
 
 +----------------+--------------+ 
 | cust_name      | cust_contact | 
 +----------------+--------------+ 
 | Coyote Inc.    | Y Lee        | 
 | Yosemite Place | Y Sam        | 
 +----------------+--------------+

如果数据量很大使用传统方式查询会很繁琐,我们可以把where自居转化成子查询来返回数据。
子查询:

 select cust_name,cust_contact  
 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_contact | 
 +----------------+--------------+ 
 | Coyote Inc.    | Y Lee        | 
 | Yosemite Place | Y Sam        | 
 +----------------+--------------+

为了执行上述select语句,MySQL实际上必须执行三条SELECT语句。
最里面的子查询返回订单列表,此列表用于其外面的子查询的where语句。
外面的子查询返回客户ID列表,此客户ID列表用于最外层查询的where语句。
最完成查询返回所需数据。

作为计算字段使用子查询
使用子查询的另一方法是创建计算字段。
例:查询customers表中每个客户的订单总数。

  1. 从customers中检索客户列表
 select cust_id,cust_name from customers;
 +---------+----------------+ 
 | cust_id | cust_name      | 
 +---------+----------------+ 
 |   10001 | Coyote Inc.    | 
 |   10002 | Mouse House    | 
 |   10003 | Wascals        | 
 |   10004 | Yosemite Place | 
 |   10005 | E Fudd         | 
 +---------+----------------+

  1. 对于检索出的每个客户统计其在orders表中的订单数目。
select count(*from orders
where cust_id = '10001';

+--------+ 
| orders | 
+--------+ 
|      2 | 
+--------+

对于每个客户的订单计算应该讲count()作为子查询

select cust_id,cust_name,    
	(select count(*)     
		from orders          
		where orders.cust_id = customers.cust_id) as orders          
		) 
from customers 
order by cust_name;

+---------+----------------+--------+ 
| cust_id | cust_name      | orders | 
+---------+----------------+--------+ 
|   10001 | Coyote Inc.    |      2 | 
|   10005 | E Fudd         |      1 | 
|   10002 | Mouse House    |      0 | 
|   10003 | Wascals        |      6 | 
|   10004 | Yosemite Place |      1 | 
+---------+----------------+--------+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值