结合快速查询的SQL将永远运行

时间:2014-03-26 06:18:10

标签: sql oracle

我正在尝试从一组payment_ids中获得最后一笔付款

表格如下 p_id pay_date amt

并且每个p_id可能会在几天内付款。

所以,我试图通过首先获得每个p_id的最后一个付款日期的表格,然后尝试查询付款日期等于上次付款日期的所有条目来实现此目的。

WITH last_date_pay as ( 
SELECT p_id as payment_id, MAX(pay_date) as last_date
FROM payments pmt
GROUP BY p_id
)
SELECT * 
FROM payments pmt
JOIN subacc i USING (p_id)

WHERE a.account in ('ACC')
AND pmt.pay_date = (SELECT last_date FROM last_date_pay WHERE p_id = last_date_pay.payment_id)

每个单独的查询几乎立即运行,而上面显示的组合查询似乎永远运行。我在这里暗示了什么?

干杯,C

2 个答案:

答案 0 :(得分:1)

使用JOIN将(SELECT last_date FROM last_date_pay WHERE p_id = last_date_pay.payment_id)移动到FROM部分

SELECT * 
FROM payments pmt
JOIN subacc i USING (p_id)
JOIN (SELECT last_date,  last_date_pay.payment_id as p_id FROM last_date_pay) sub USING (p_id)
WHERE a.account in ('ACC')
AND pmt.pay_date =sub.last_date

答案 1 :(得分:0)

您是否尝试过只访问该表的查询?

SELECT * FROM (
  SELECT pmt.*
        ,MAX(pmt.pay_date) OVER (PARTITION BY pmt.p_id) AS last_date
  FROM   payments pmt
) JOIN subacc i USING (p_id)
WHERE i.account in ('ACC') AND pmt.pay_date = pmt.last_date;

(我假设account位于subacc表中)