查询定购了23号产品20件以上的顾客的列表
sql语句1:
use northwind
select orderid,customid
      from orders AS or1
      where 20<(select quantity 
from [order details] AS od
where or1.orderid=od.orderid
and od.productid=23)
这是相关子查询,相关子查询的执行方式是针对外层的每一条记录执行里层的查询,我写了另外两条sql语句:
use northwind
1.select quantity, od.orderid into _temp
   from [order details] as od
   where od.orderid in (select orderid from orders)
          and od.productid=23
2. select orderid,customerid
from orders
where 20<(select quantity from _temp
where orders.orderid=_temp.orderid)
我执行了下,结果是一样的,但是我不知道这样改是否是等价的,想证明下,望高手赐教啊:)

解决方案 »

  1.   

    不过都有问题
    如果
    orders:[order   details] === 1:N
    子查询会出错
    所以,这却语句应该是
     
    select   orderid,customid 
                from   orders   AS   or1 
                where  exists (select   1   
    from   [order   details]   AS   od 
    where   or1.orderid=od.orderid 
    and   od.productid=23
    and od.quantity>20
      

  2.   

    两个语句还是有区别的,第二个语句应该加上drop table _temp 否则第二次执行就出错了