是否有更好,更优化的方法来执行此SQL查询?

时间:2015-11-05 22:56:37

标签: sql sql-server

我有一个SQL查询,我们在其中选择产品列表,但还需要查询订单表以查找已售出的数量。有没有更有效的方法来检索没有子查询的numberSold总和?

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 tProducts.langID=@langID
ORDER BY tProducts.BaseUnitPrice ASC

2 个答案:

答案 0 :(得分:2)

如果遇到性能问题,那么索引可能会有所帮助。

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

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

答案 1 :(得分: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 
     tProducts.langID=@langID
ORDER BY tProducts.BaseUnitPrice ASC