我有一个 SP,它从包含 UNION 的查询中返回分页数据。这正在杀死我的数据库并且有时需要 30 秒才能运行,我在这里遗漏了一些明显的东西吗?我能做些什么来提高它的性能?
涉及的表:产品、类别、类别产品
目标:任何不在类别中或已从类别中删除的产品联合当前在一个类别中的所有产品,并为 Web 服务在这些产品上翻页。
我加入的所有列都有索引,数据库中有 427,996 个产品、6148 个类别和 409,691 个类别产品。
这是我的查询,运行时间在 6 到 30 秒之间:
SELECT * FROM (
SELECT ROW_NUMBER() OVER(ORDER BY Products.ItemID, Products.ManufacturerID) AS RowNum, *
FROM
(
SELECT Products.*,
CategoryID = NULL, CategoryName = NULL,
CategoryProductID = NULL,
ContainerMinimumQuantity =
CASE COALESCE(Products.ContainerMinQty, 0)
WHEN 0 THEN Products.OrderMinimumQuantity
ELSE Products.ContainerMinQty
END
Products.IsDeleted,
SortOrder = NULL
FROM CategoryProducts RIGHT OUTER JOIN Products
ON CategoryProducts.ManufacturerID = Products.ManufacturerID
AND CategoryProducts.ItemID = Products.ItemID
WHERE (Products.ManufacturerID = @ManufacturerID)
AND (Products.ModifiedOn > @tStamp )
AND ((CategoryProducts.IsDeleted = 1) OR (CategoryProducts.IsDeleted IS NULL))
UNION
SELECT Products.*,
CategoryProducts.CategoryID , CategoryProducts.CategoryName,
CategoryProducts.CategoryProductID ,
ContainerMinimumQuantity =
CASE COALESCE(Products.ContainerMinQty, 0)
WHEN 0 THEN Products.OrderMinimumQuantity
ELSE Products.ContainerMinQty
END
CategoryProducts.IsDeleted,
CategoryProducts.SortOrder
FROM Categories INNER JOIN
CategoryProducts ON Categories.CategoryID = CategoryProducts.CategoryID INNER JOIN
Products ON CategoryProducts.ManufacturerID = Products.ManufacturerID
AND CategoryProducts.ItemID = Products.ItemID
WHERE (Products.ManufacturerID = @ManufacturerID)
AND (Products.ModifiedOn > @tStamp OR CategoryProducts.ModifiedOn > @tStamp))
AS Products) AS C
WHERE RowNum >= @StartRow AND RowNum <= @EndRow
任何见解将不胜感激。