第11课 使用子查询使用计算字段作为子查询

时间:2022-06-07
本文章向大家介绍第11课 使用子查询使用计算字段作为子查询,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我们考虑一个问题,列出订购物品‘RGAN01’的所有顾客的信息,那我们应该用怎样的信息检索?

  • 检索包含物品‘RGAN01’的所有订单号
  • 从这个订单号里到orders表里检索出custid
  • 再根据custid从customers的表里检索顾客的信息

上面三个步骤每个步骤都可以单独作为一个查询来执行,这就出现了子查询的定义。

不使用子查询“

select order_num
from orderitems
where prod_id = 'RGAN01';

select cust_id 
from orders
where order_num in (20007,20008)

使用子查询:

select cust_id
from orders
where order_num in (select order_num
from orderitems
where prod_id = 'RGAN01');

使用计算字段作为子查询

假设有这么一个问题,显示customers表中的每个顾客订单的总数:

  • 第一步,自然是检索出所有顾客的列表
  • 然后对于每个顾客统计其在orders表中的订单数目
select customers.cust_name, customers.cust_state,(
    select count(*)
    from orders
    where orders.cust_id = customers.cust_id
) as orders
from customers
order by cust_name;