SQL必知必会-笔记(七)查询,联结

子查询

即嵌套在其他查询中的查询

  • 表结构说明:每个订单包含订单编号,客户ID,订单日期,在Orders表中。各订单的物品存储在相关的OrderItems表中,Orders表中不存储客户信息,只存储客户ID。客户实际信息存储在Customers表中。
  • 问题1:检索出订购物品RGAN01的所有顾客

  • 解:
    • 步骤一:检索出包含物品RGAN01的订单
    select order_num from OrderItems where prod_id = 'RGAN01';
    可以得到,
    • 步骤二:检索出和订单号20007,20008相关的顾客
    select cust_id from Orders where order_num in (20007,20008);
    可以得到,
    • 步骤三:检索出这些客户ID的顾客信息
    select cust_name,cust_contact from Customers where cust_id in ('1000000004','1000000005');
    可以得到,
  • 总结:

    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 = 'RGAN01'));

    需要注意的地方:1. 作为子查询的SELECT语句只能查询单个列,企图检索多个列将返回错误;2. 对于能嵌套的子查询的数目没有限制,不过在实际使用的时候由于性能的限制,不能嵌套太多的子查询。

  • 问题2:显示Custormers表中每个顾客的订单总数

  • 解:
    • 步骤一:检索出Custormers表中的顾客列表
      select cust_name,cust_state,cust_id from Customers order by cust_name;
    • 步骤二:对于检索出的顾客,检索其在Orders表中的订单数目
    select count(*) from Orders where cust_id = '1000000003';
  • 总结:
   select cust_name, cust_state , (select count(*) from Orders where Orders.cust_id = Customers.cust_id) from Customers order by cust_name;

其中,where Orders.cust_id = Customers.cust_id表示比较从Orders表中的cust_id和当前正从Customers表中检索出的cust_id。

另外,虽然样例可以完成需求,但并不是解决这种数据检索的最有效方法,后面讲到JOIN方法时我们会重新做这道题。


联结表

如果数据存储在多个表中,怎样用一句SELECT语句就检索出数据呢?答案是,使用联结。

猜你喜欢

转载自www.cnblogs.com/xLI4n/p/10346323.html