SQL嵌套查询

SQL嵌套查询

利用自查询进行行过滤(in)

订单表orders

orders订单表

顾客表 customers

customers顾客表

订单商品表orderitems

orderitems订单商品表

#列出订购物品RGAN01的所有顾客
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'));

-作为自查询的SELECT语句只能查询单个列

作为计算字段使用子查询

显示customers表中每个顾客的订单总数

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

执行结果
执行结果

如何理解orders表中子查询where orders.cust_id= customers.cust_id?

  1. orders表中的cust_id 字段为
    orders.cust_id
  2. customers表中的cust_id字段为
    customers.cust_id

  3. 自查询中的select列表为count(*)

  4. 其含义为对customers表(上一级查询中的表)中cust_id列的所有项(1000000001、1000000002、1000000003、1000000004、1000000005)按照orders表(子查询的表)中cust_id列出现的次数进行计数

5.该子查询对检索出来的每个顾客执行一次, 得到结果
cust_id
1000000001 2
1000000002 0
1000000003 1
1000000004 1
1000000005 1

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值