SQL嵌套查询

来源:互联网 发布:dreamhost java 编辑:程序博客网 时间:2024/06/05 06:56

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