ade*_*dek 11 sql t-sql sql-server full-text-search sql-server-2012
我正在尝试编写一个数据库大小的查询结果分页.正如SQL Server 2012所提供的OFFSET/FETCH,我正在使用它.但是在我将语句添加到查询后,需要花费10倍的时间.
查询:
SELECT
p.ShopId,
count(1) as ProductsQuantity,
MIN(LastPrice) as MinPrice,
MAX(LastPrice) as MaxPrice
FROM Product2 p WITH (NOLOCK)
INNER JOIN
CONTAINSTABLE(Product2, ProductName, 'czarny') AS KEY_TBL
ON KEY_TBL.[key]=p.Id
WHERE
(p.LastStatus > 0 OR p.LastStatus = -1)
GROUP BY p.ShopId
ORDER BY p.ShopId asc
SELECT
p.ShopId,
count(1) as ProductsQuantity,
MIN(LastPrice) as MinPrice,
MAX(LastPrice) as MaxPrice
FROM Product2 p WITH (NOLOCK)
INNER JOIN
CONTAINSTABLE(Product2, ProductName, 'czarny') AS KEY_TBL
ON KEY_TBL.[key]=p.Id
WHERE
(p.LastStatus > 0 OR p.LastStatus = -1)
GROUP BY p.ShopId
ORDER BY p.ShopId asc
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY
Run Code Online (Sandbox Code Playgroud)
第一个查询在3秒内返回结果,第二个查询在47秒内返回.执行计划是不同的,第二个的成本仅评估为7%,对我来说完全没有意义:

我需要帮助如何提高分页的性能.
如果没有掌握架构和数据,就很难提出建议。在这 3 秒内,您至少应该能够做一件事。第一次查询需要 47 秒。第二个,将第一个查询的结果放入临时表中,然后将其用于order by ... offset fetch next:
create table #tmp (Id int not NULL, Quantity int, MinPrice decimal(10,4), MaxPrice decimal(10,4), primary key clustered (Id))
insert into #tmp
SELECT
p.ShopId,
count(1) as ProductsQuantity,
MIN(LastPrice) as MinPrice,
MAX(LastPrice) as MaxPrice
FROM Product2 p WITH (NOLOCK)
INNER JOIN
CONTAINSTABLE(Product2, ProductName, 'czarny') AS KEY_TBL
ON KEY_TBL.[key]=p.Id
WHERE
(p.LastStatus > 0 OR p.LastStatus = -1)
GROUP BY p.ShopId
select ShopId, ProductsQuantity, MinPrice, MaxPrice
from #tmp
ORDER BY ShopId asc
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY
Run Code Online (Sandbox Code Playgroud)