子查询

本文详细介绍了SQL中的子查询使用方法,包括使用比较运算符any或all进行子查询、使用in或not in进行成员资格测试以及使用exists或not exists检查子查询结果的存在性。通过实例展示了如何找出金额最高的订单、特定条件下的销售记录以及尚未有任何销售记录的库存产品。

 子查询
1
select ... where 列或运算式 比较运算运算【any|all](子查询)
   
只要主查询中列或运算式与子查询所得结果中任一(any)或全部(all)数据符合比较条件的话则主查询的结果为我们要的数据

       选出不同的人金额最高的订单
    select *  from  sales a
    where tomat=(select max(totmat) from sales  where name=a.name)
    
    select sale_id,tot_amt
    from sales 
    where tot_amt>any(select tot_amt from sales where sale_id='e0013'and 'order_date='1996/11/10')
   
2。select ...where 列或运算式[not] in (子查询)
    只要主查询中列或运算式是在(不在)子查询所得结果列表中的话,则主查询的结果为我们要的数据
    select sales_id,tot_amt
    from sales 
    where sale _id  in(select sale_id from employee where sex='F')
3.select ...where [not] exists (  子查询)
  子查询的结果至少存在一条数据时,则主查询的结果为我们要的数据。(exists)或自查询的结果找不到数据时,则主查询的结果为我们要的数据(not exists)
 我们经常查询的两个表有多少重复的记录就用这个
 以下范例让你找出滞销的产品,也就是尚未有任何销售记录的库存产品。此范例主要是查询以库文件中的每一条产品代码到销售明细表中去查询,如果查询不到任何一条,表示该产品未曾卖出任何一件。
  select * from stock a
  where not exists(select * from sale_item b
                          where a.prod_id=b.prod_id and a.stup_id=b.stup_id)

 select emp_no,emp_name from employee
 from employee a
 where (select sum(tot_amt) from sales b where a.sale_id=b.emp_no)<200000

 

转载于:https://www.cnblogs.com/shihao/archive/2009/05/20/1467795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值