我有一個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
標記爲答案。建議的索引實際上是最好的解決方案,原始子查詢似乎是最優的 – redoc