首页 > 数据库技术 > 详细

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

时间:2019-02-01 17:40:47      阅读:199      评论:0      收藏:0      [点我收藏+]

子查询

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

  • 表结构说明:每个订单包含订单编号,客户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方法时我们会重新做这道题。


联结表

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

原文:https://www.cnblogs.com/xLI4n/p/10346323.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!