外部通过游标加入查询

时间:2014-05-11 20:47:49

标签: mysql sql cursor left-join

我有以下查询:

(
     select  f.Product, bpsrelation.bps, f.Week ForecastWeek, 
             f.FC Forecast, `Order qty`  quantity, 
             s.FC Sales, s.Week salesWeek, s.`Plant Code`, f.`APO Location` 
     from forecastnew f
     right outer join bpsrelation on bpsrelation.Product = f.Product
     right outer join sales s on bpsrelation.bps = s.BPS and f.Week = s.Week 
                             and s.`PLant Code` = f.`APO Location`
     right outer join orders on orders.Product = f.Product
     group by s.Week, s.`PLant Code`,s.Customer,s.bps
) 
union
(
     select  f.Product, bpsrelation.bps, f.Week ForecastWeek, 
             f.FC Forecast, `Order qty`     quantity, 
             s.FC Sales, s.Week salesWeek, s.`Plant Code`, f.`APO Location` 
     from forecastnew f
     left outer join orders on orders.Product = f.Product
     left outer join bpsrelation on bpsrelation.Product = f.Product
     left outer join sales s on bpsrelation.bps = s.BPS 
                             and f.Week = s.Week and s.`PLant Code` = f.`APO Location`
     where f.`APO Location` is null
     group by s.Week, f.`APO Location`, s.Customer,s.bps
); 

扩展的解释如下:

1   PRIMARY orders  ALL                 33335   100.00  Using         temporary; Using filesort
1   PRIMARY f   ref idx_forecastnew_Product idx_forecastnew_Product 23          demandplaning.orders.Product    103 100.00  
1   PRIMARY bpsrelation ref idx_bpsrelation_Product,idx_bpsrelation_bps idx_bpsrelation_Product 23  demandplaning.f.Product 1   100.00  
1   PRIMARY s   ref idx_sales_BPS   idx_sales_BPS   33  demandplaning.bpsrelation.bps   41  100.00  Using where
2   UNION   f   ALL                 329325  100.00  Using where; Using temporary; Using filesort
2   UNION   orders  ref idx_orders_Product  idx_orders_Product  23  demandplaning.f.Product 64  100.00  
2   UNION   bpsrelation ref idx_bpsrelation_Product idx_bpsrelation_Product 23  demandplaning.f.Product 1   100.00  
2   UNION   s   ref idx_sales_BPS   idx_sales_BPS   33  demandplaning.bpsrelation.bps   41  100.00  Using where
    UNION RESULT    <union1,2>  ALL                             Using temporary

预测和销售表需要通过工厂代码,周和产品加入。 这需要很多时间。我搜索了stackoverflow和互联网,建议用foreach或cursor执行此操作。任何人都可以帮我吗?

非常感谢。

0 个答案:

没有答案