SQL请求。如何让它更快地运作?

时间:2017-05-31 10:13:50

标签: sql-server

我有sql请求需要花费很多时间才能执行,有什么建议可以让它更快吗?

DECLARE @Today DATETIME; 
DECLARE @TwoWeeksAgo 
DATETIME; SET @Today = GETDATE();
SET @TwoWeeksAgo = DATEADD(DAY, -14, GETDATE()); 
SELECT TOP ${selectSalesByMall} s.title, s.imageUrl, count(sv.saleid) as mostViewPeriod14Days, s.guid, br.title as brand, s.id as saleId, stm.mallId
FROM dbo.Sales s  
INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON s.id = b_key.saleId 
INNER JOIN dbo.Brands br ON s.BrandId = br.Id 
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId 
INNER JOIN dbo.SalesToMall stm ON s.id = stm.saleId 
LEFT JOIN dbo.SaleView sv2 on sv2.id = sv.id and sv2.userId = ${user['userID']} 
WHERE sv.Date 
BETWEEN @TwoWeeksAgo 
AND @Today 
AND sv2.id IS NULL 
AND s.isActive = 1
AND stm.mallId = ${user['mallId']}
AND br.id != ${user['favBrand']['brandId']}
AND s.id NOT IN (SELECT uess.saleID FROM dbo.UsersEmailsSalesSent uess WHERE uess.userID = ${user['userID']})
GROUP BY s.title, s.imageUrl, s.guid, br.title, s.id, stm.mallId 
ORDER BY mostViewPeriod14Days DESC

1 个答案:

答案 0 :(得分:1)

一个改进可能是改变"而不是"到"不存在":

DECLARE @Today DATETIME; 
DECLARE @TwoWeeksAgo 
DATETIME; SET @Today = GETDATE();
SET @TwoWeeksAgo = DATEADD(DAY, -14, GETDATE()); 
SELECT TOP ${selectSalesByMall} s.title, s.imageUrl, count(sv.saleid) as mostViewPeriod14Days, s.guid, br.title as brand, s.id as saleId, stm.mallId
FROM dbo.Sales s  
INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON s.id = b_key.saleId 
INNER JOIN dbo.Brands br ON s.BrandId = br.Id 
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId 
INNER JOIN dbo.SalesToMall stm ON s.id = stm.saleId 
LEFT JOIN dbo.SaleView sv2 on sv2.id = sv.id and sv2.userId = ${user['userID']} 
WHERE sv.Date 
BETWEEN @TwoWeeksAgo 
AND @Today 
AND sv2.id IS NULL 
AND s.isActive = 1
AND stm.mallId = ${user['mallId']}
AND br.id != ${user['favBrand']['brandId']}
AND
NOT EXISTS (SELECT uess.saleID FROM dbo.UsersEmailsSalesSent uess WHERE uess.userID = ${user['userID']} and  s.id=uess.saleID)
GROUP BY s.title, s.imageUrl, s.guid, br.title, s.id, stm.mallId 
ORDER BY mostViewPeriod14Days DESC