我有一个 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
最佳答案
如果您遇到性能问题,那么索引也许会有所帮助。
子查询的最佳索引是:tOrderDetails(productid, orderid, amount)
和 tOrder(orderid, isTestOrder)
。
外部查询的最佳索引是:tProducts(ProjectId, isVisibleId, SalesContainerTypeID, langID, BaseUnitPrice, ImageID)
和 tProjectImages(Id)
。
关于sql - 有没有更好、更优化的方法来执行此 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556383/