2015-11-05 89 views
2

我有一個SQL查詢,我們正在選擇產品列表,但也需要查詢一個訂單表,以找出有多少已售出。有沒有更有效的方式來檢索沒有子查詢numberSold總和?是否有更好,更優化的方式來執行此SQL查詢?

SELECT tProducts.ID as ID, 
tProducts.Name, 
tProducts.Description, 
Highlights=Replace(Replace(tProducts.Highlights, '##productdeliverydate##', convert(varchar, @ProjectReleaseDt, 101)),'##productltdedition##', @productltdedition), 
tProducts.isLocked as isLocked, 
tProducts.isVisible as isVisible, 
tProducts.ImageID as ImageID, 
tProducts.ShippingYN as ShippingYN, 
tProducts.LastDateUpdate as LastDateUpdate, 
tProducts.BaseUnitPrice as Price, 
    FileExtension = case tProjectImages.FileExtention 
    WHEN tProjectImages.FileExtention then tProjectImages.FileExtention 
    ELSE '.none' 
    END, 
    @ImagePath as ImagePath, 
    @ImageServerPath as ExternalServerPath, 
    @ThumbExt as ThumbnailExtension,  
    tProducts.SalesContainerTypeID, 
    tProducts.ListOrder, 
    tProducts.isParticipantListed, 
    tProducts.LimitQuantity, 
    tPRoducts.isFeature, 
    numbersold=(SELECT sum(quantity) 
        from tOrderDetails 
        JOIN tOrders 
        on tORders.OrderID=tORderDetails.ORderID 
       where productID=tProducts.ID 
        and tOrders.isTestOrder=0), 
FROM tProducts 
LEFT JOIN tProjectImages ON tProducts.ImageID = tProjectImages.ID 
WHERE tProducts.ProjectID = @projectID 
and tProducts.isVisible=1 
and tProducts.SalesContainerTypeID = 6 
and [email protected] 
ORDER BY tProducts.BaseUnitPrice ASC 

回答

2

如果遇到性能問題,那麼也許指數會有所幫助。

子查詢的最佳索引是:tOrderDetails(productid, orderid, quantity)tOrder(orderid, isTestOrder)

外部查詢的最佳索引是:tProducts(ProjectId, isVisibleId, SalesContainerTypeID, langID, BaseUnitPrice, ImageID)tProjectImages(Id)

+3

標記爲答案。建議的索引實際上是最好的解決方案,原始子查詢似乎是最優的 – redoc

1

我不確定它是否更有效率(您想檢查執行計劃)。但這裏有一個替代版本的outer join一個子查詢:

SELECT ... 
    numbersold=t.qty, 
FROM tProducts 
    LEFT JOIN tProjectImages ON tProducts.ImageID = tProjectImages.ID 
    LEFT JOIN (
     SELECT sum(quantity) qty, productID 
     FROM tOrderDetails 
      JOIN tOrders on tORders.OrderID =tORderDetails.ORderID 
     GROUP BY productID 
    ) t ON t.productID=tProducts.ID and tOrders.isTestOrder=0 
WHERE tProducts.ProjectID = @projectID and 
    tProducts.isVisible=1 and 
    tProducts.SalesContainerTypeID = 6 and 
    [email protected] 
ORDER BY tProducts.BaseUnitPrice ASC 
+0

原始查詢可能更有效。此查詢彙總所有訂單明細和訂單。根據「where」子句中的所有限制,外部查詢可能會將數據限制爲幾個命令。相關的子查詢只進行必要的計算。 –

+0

@sgeddes - 謝謝我會試一試。戈登 - 不幸的是它可能是。我厭惡子查詢:) – redoc

+0

@GordonLinoff - 感謝您的信息。我不確定,但是想知道'outer join/subquery'只會執行一次,其中相關的子查詢會針對每個匹配執行。很高興知道。和所有的績效問題一樣,我通常會審查執行計劃並相應地推進。再次感謝。 – sgeddes

相關問題