利用子查询进行过滤
需要订购物品TNT2的所有客户
- 检索包含物品TNT2的所有订单的编号
- 检索具有前一步骤列出的订单编号的所有客户的ID
- 检索前一步骤返回的所有客户ID的客户信息
列出包含此物品的订单
select order_num
from orderitems
where prod_id = 'TNT2' ;
查询具有订单a,b的客户ID
select cust_id
from orders
where order_num IN (a,b);
把第一个查询变为子查询组合两个查询
select cust_id
from orders
where order_num IN ( select order_num
from orderitems
where prod_id = 'TNT2' ;);
分析
- 子查询总是从内向外处理
- 先执行查出订单,传入IN内
- 再执行外循环
检索这些客户的ID的客户信息
select cust_name , cust_contact
from customers
where cust_id IN (10001,10004);
子查询
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' ;););
分析
- 最里面的子查询返回订单号列表,次列表用于其外面的子查询的where子句
- 外面的子查询返回客户ID列表,此客户ID列表用于最外层的where子句
- 最外面查询确实返回所需的数据
- 对于嵌套的子查询的数目是没有限制,不过实际使用时由于性能的限制,不能嵌套太多的查询
作为计算字段使用子查询
需要显示customers表中每个客户的订单总数
- 从customers表中检索客户列表
- 对于检索出的每个客户,统计其在orders表中的订单数目。
对客户10001的订单进行计数
select COUNT(*) AS orders
from orders
where cust_id = 10001;
为了对每个客户执行COUNT(*)计算,应该将COUNT(*)作为一个子查询
select cust_name,
cust_state,
(select COUNT(*)
from orders
where orders.cust_id = customers.cust_id) AS orders
from customers
order by cust_name;
分析
- 运用完全限定列名
- 相关子查询:涉及外部查询的子查询
逐渐总价子查询来建立查询
- 用子查询建立(测试)查询的最可靠的方法是逐渐进行
- 建立和测试最内层的查询
- 硬编码数据建立和测试外部查询