我有一個我正在運行的sproc,我試圖使用分頁,但也返回整個產品計數。這是「工作」,但問題是,當我拿出totalCount CTE並從最終的SELECT中刪除它時,我的貼片在〜50ms內運行。當我把它放在那裏時,我的查詢需要7-8秒。如果我抓取所有記錄,這是一個很大的查詢,但想法只抓取我需要的頁面,但我需要返回總記錄。有沒有更有效的方法來做到這一點?CTE分頁,與計數
/**主搜索塊**/
WITH search_results AS
(
SELECT DISTINCT
ROW_NUMBER() OVER (ORDER BY @sortExpression) as rowNumber,
products.pid,
brands.bid,
brands.brand_name,
products.model,
products.name,
products.searchedprice
products.status
FROM products WITH (NOLOCK)
JOIN brands WITH (NOLOCK) ON products.bid=brands.bid
WHERE
(
CONTAINS(products.*,@inflectionSearchText)
OR
CONTAINS(brands.Brand_Name,@inflectionSearchText)
)
AND
products.productstatus=1
AND
brands.brandstatus=1
AND
products.searchedprice BETWEEN @fromprice TO @toprice
),
totalCount AS
(SELECT COUNT(*) Total FROM search_results)
SELECT *
FROM search_results, totalCount
WHERE
rowNumber BETWEEN ((@pageNumber-1)*@pageSize)+1
AND ((@pageNumber-1)*@pageSize)[email protected]
ORDER BY products.model
一個DISTINCT與ROW_NUMBER(),並沒有分組?爲什麼? –
你看過執行計劃,特別是'search_results'和'totalCount'之間的最後一個'JOIN'嗎?將返回一個'OUTPUT'參數的總數是否足夠?它會接近'Max(rowNumber)'嗎? – HABO