2014-11-21 65 views
0

在我的查詢中,我使用了一個子查詢,該子查詢獲得給定產品的第二個最後一個報價日期。MySQL優化使用WHERE子句的子查詢?

這裏是我的子查詢:

LEFT JOIN (SELECT product_id, MAX(offer_date) AS sec_last_date 
      FROM t_offers AS s1 
      WHERE offer_date < (SELECT MAX(offer_date) 
           FROM t_offers 
           WHERE product_id=s1.product_id) 
      GROUP BY product_id) AS t2 ON t2.product_id=p.id 
LEFT JOIN t_offers AS o2 ON o2.product_id=t2.product_id AND 
          o2.offer_date=t2.sec_last_date 

它工作正常,但是目前是隻在t_offers表幾行。

由於WHERE子句迫使MySQL爲每個product_id迭代t_offers表,所以它可能不會在數千行或數百萬行中發揮作用。

我該如何優化這個子查詢?

+0

不知這個作品真的很好,你說的。例如,這沒有意義'product_id = s1.product_id',因爲它與'product_id = product_id'相同。 – 2014-11-21 10:03:04

+0

是的,我可以刪除product_id = product_id並得到相同的結果。 但是我仍然在我的子查詢中有一個WHERE,所以pb保持不變。 – Duddy67 2014-11-21 11:37:07

回答

0

子查詢通常是不能在MySQL中,由於大的連接不使用索引。

但是它可能是值得嘗試的一個子查詢與聯接,而不是一個子查詢中的子查詢: -

LEFT JOIN (SELECT s1.product_id, MAX(s1.offer_date) AS sec_last_date 
      FROM t_offers AS s1 
      INNER JOIN t_offers AS s2 
      ON s2.product_id = s1.product_id 
      AND s2.offer_date > s1.offer_date 
      GROUP BY s1.product_id) AS t2 ON t2.product_id=p.id 
+0

聽起來不錯!我沒有想到在左連接的子查詢中放置一個內連接。通過這種方式,WHERE子句問題似乎可以解決。 – Duddy67 2014-11-21 12:45:36

0

你就不能排序的報價日期,並獲得最新2類似:

select product_id, offer_date 
from your table 
order by offer_Date desc 
limit 2