2014-06-20 29 views
1

如何改進我的查詢,因爲它將超時異常。有人可以幫助我改進查詢...?查詢可以改進,因爲它要超時異常

UPDATE pdtdeliveryTable p SET p.OrderID = IFNULL 
( 
    (SELECT OrderID from OrderTable o where o.DiagramID=p.DiagramID AND o.DeliveryDate= 
    (
     Select min(o2.DeliveryDate) from OrderTable o2 where o2.DiagramId=o.DiagramID Order by o2.DeliveryDate 
    )Limit 1),0 
) 
where p.OrderID=0; 

回答

1

試試這個:

UPDATE pdtdeliveryTable p 
LEFT OUTER JOIN (SELECT o.DiagramID, o.OrderID FROM OrderTable o 
       INNER JOIN (SELECT DiagramID, MIN(DeliveryDate) DeliveryDate 
           FROM OrderTable GROUP BY DiagramID 
          ) AS A ON o.DiagramID = A.DiagramID AND o.DeliveryDate = A.DeliveryDate 
       ) AS A ON A.DiagramID = p.DiagramID 
SET p.OrderID = IFNULL(A.OrderID, 0); 

OR

UPDATE pdtdeliveryTable p 
LEFT OUTER JOIN (SELECT DiagramID, OrderID 
        FROM (SELECT DiagramID, OrderID, DeliveryDate FROM OrderTable ORDER BY DiagramID, DeliveryDate) AS A 
        GROUP BY DiagramID 
       ) AS A ON p.DiagramID = A.DiagramID 
SET p.OrderID = IFNULL(A.OrderID, 0); 
+0

@Sarharsh但查詢不conidering最低DeliveryDate其採取的最頂層值的第二個查詢。 – neo