我有一个查询,在 WHERE 子句中有很多条件连接 4 个表。该查询还包括数字列上的 ORDER BY 子句。返回需要 6 秒,这太长了,我需要加快速度。令人惊讶的是,我发现如果删除 ORDER BY 子句需要 2 秒。为什么 order by 会产生如此巨大的差异以及如何优化它?我使用的是 SQL Server 2005。非常感谢。
由于我正在清除执行计划缓存,因此我无法确认 ORDER BY 有很大的不同。但是,您能否解释一下如何加快速度?查询如下(为简单起见,有“SELECT *”但我只选择了我需要的那些)。
SELECT *
FROM View_Product_Joined j
INNER JOIN [dbo].[OPR_PriceLookup] pl on pl.siteID = NodeSiteID and pl.skuid = j.skuid
LEFT JOIN [dbo].[OPR_InventoryRules] irp on irp.ID = pl.SkuID and irp.InventoryRulesType = 'Product'
LEFT JOIN [dbo].[OPR_InventoryRules] irs on irs.ID = pl.siteID and irs.InventoryRulesType = 'Store'
WHERE (((((SiteName = N'EcommerceSite') AND (Published = 1)) AND (DocumentCulture = N'en-GB')) AND (NodeAliasPath LIKE N'/Products/Cats/Computers/Computer-servers/%')) AND ((NodeSKUID IS NOT NULL) AND (SKUEnabled = 1) AND pl.PriceLookupID in (select TOP 1 PriceLookupID from OPR_PriceLookup pl2 where pl.skuid = pl2.skuid and (pl2.RoleID = -1 or pl2.RoleId = 13) order by pl2.RoleID desc)))
ORDER BY NodeOrder ASC
最佳答案
Why the order by makes so massive difference and how to optimize it?
ORDER BY
需要对结果集进行排序,如果结果集很大,可能需要很长时间。要优化它,您可能需要正确索引表。
然而,索引访问路径有其缺点,因此它甚至可能需要更长的时间。
如果您的查询中有除 equijoins 或范围谓词(如
<
、 >
或 BETWEEN
或 GROUP BY
子句)以外的其他内容,则用于 ORDER BY
的索引可能会阻止使用其他索引。如果您发布查询,我可能会告诉您如何优化它。
更新:
重写查询:
SELECT *
FROM View_Product_Joined j
LEFT JOIN
[dbo].[OPR_InventoryRules] irp
ON irp.ID = j.skuid
AND irp.InventoryRulesType = 'Product'
LEFT JOIN
[dbo].[OPR_InventoryRules] irs
ON irs.ID = j.NodeSiteID
AND irs.InventoryRulesType = 'Store'
CROSS APPLY
(
SELECT TOP 1 *
FROM OPR_PriceLookup pl
WHERE pl.siteID = j.NodeSiteID
AND pl.skuid = j.skuid
AND pl.RoleID IN (-1, 13)
ORDER BY
pl.RoleID desc
) pl
WHERE SiteName = N'EcommerceSite'
AND Published = 1
AND DocumentCulture = N'en-GB'
AND NodeAliasPath LIKE N'/Products/Cats/Computers/Computer-servers/%'
AND NodeSKUID IS NOT NULL
AND SKUEnabled = 1
ORDER BY
NodeOrder ASC
关系
View_Product_Joined
,顾名思义,大概是一种观点。你能把它的定义贴出来吗?
如果它是可索引的,您可能会受益于在
View_Product_Joined (SiteName, Published, DocumentCulture, SKUEnabled, NodeOrder)
上创建索引。 .
关于sql - 由于 ORDER BY 子句导致 SQL 查询性能不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2139980/