2014-11-21 63 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