如何引用和重用相关的子查询?

时间:2013-05-14 16:39:27

标签: correlated-subquery

想象一下交易表和cds_coupon表加入了交易ID;优惠券表也有结算日期和结算金额。所需的查询是获取下一张优惠券的金额和日期。

    select t.tradeId AS tradeId,
(
  select settlement_date from cds_coupon e 
  where t.tradeId=e.tradeId 
  and e.settlement_date = (select min(settlement_date) from cds_coupon ei where ei.tradeId = t.tradeId  and ei.settlement_date > sysdate )
)  AS settlement_date,
( 
  select settlement_amount from cds_coupon e 
  where t.tradeId=e.tradeId 
  and e.settlement_date = (select min(settlement_date) from cds_coupon ei where ei.tradeId = t.tradeId and ei.settlement_date > sysdate )
)  AS settlement_amount, 
   FROM Trade t

可以看出,两个相同的核心化水平只进行了两次,只是为了抓住一个不同的领域 - 一次抓住结算日期,一次抓住结算金额。因此问题 - 如何引用和重用核心子查询?

2 个答案:

答案 0 :(得分:0)

如果使用SQL Server,您可以使用Common Table Expression (CTE)

;WITH SettlementDates ()
AS
(
    SELECT tradeId, MIN(settlement_date) as settlement_date
    FROM cds_coupon  
    WHERE settlement_date > sysdate
    GROUP BY tradeId
)

SELECT e.trade_id, e.settlement_date, e.settlement_amount
FROM cds_coupon e
JOIN SettlementDates sd 
    ON (e.trade_id = sd.trade_id)
   AND (e.settlement_date = sd.settlement_date)

答案 1 :(得分:0)

使用JOIN而不是相关子查询:

select t.tradeId, e.settlement_date, e.settlement_amount
from Trade t
join (select ei.tradeId, ei.settlement_date, ei.settlement_amount
      from cds_coupon ei
      join (select tradeId, min(settlement_date) min_date
            from cds_coupon
            where settlement_date > sysdate
            group by tradeId) emin
      on ei.tradeId = e.tradeId and ei.settlement_date = min_date) e
on t.tradeId = e.tradeId

子查询是一种标准习惯用法,用于查找包含字段最小值或最大值的行。