我正在尝试使用sql中的ROW_NUMBER()在asp.net中实现gridview的自定义分页。下面的(经典)查询效果很好,但是它的性能不是那么好,因为我必须将整个表复制到一个新表,然后从新表中选择20个记录。如果没有分页,有时甚至可以更好地工作,只需一次检索所有记录。我试图在where子句中使用ROW_NUMBER(),但是sql不允许我这样做。如何改进下面的查询?你的建议是什么?我想我需要找到一种方法来消除将整个数据集复制到新表的过程,但是如何?
SELECT PostId, Message, (ROW_NUMBER() OVER (ORDER BY LastUpdateDateTime DESC)) as Row
INTO #Results
FROM Posts
WHERE Posts.TimePointId=@TimePointId AND IsFixed=0
ORDER BY LastUpdateDateTime DESC
-----------------------------------------------------
SELECT * FROM #Results
WHERE Row BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
DROP TABLE #Results
答案 0 :(得分:2)
你真的不需要使用临时表来进行这样简单的操作,只需使用子查询或CTE。
使用子查询
SELECT *
FROM (
SELECT PostId, Message, (ROW_NUMBER() OVER (ORDER BY LastUpdateDateTime DESC)) as Row
FROM Posts
WHERE Posts.TimePointId=@TimePointId AND IsFixed=0
) Sub
WHERE Row BETWEEN(@PageIndex -1) * @PageSize + 1
AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
使用CTE
;WITH CTE
AS
(
SELECT PostId, Message, (ROW_NUMBER() OVER (ORDER BY LastUpdateDateTime DESC)) as Row
FROM Posts
WHERE Posts.TimePointId=@TimePointId AND IsFixed=0
)
SELECT *
FROM CTE
WHERE Row BETWEEN(@PageIndex -1) * @PageSize + 1
AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
答案 1 :(得分:1)
我不确定这是否会解决您的性能问题,您可以使用子查询而不是临时表:
SELECT p.*
FROM (SELECT PostId, Message, (ROW_NUMBER() OVER (ORDER BY LastUpdateDateTime DESC)) as Row
FROM Posts
WHERE Posts.TimePointId=@TimePointId AND IsFixed=0
) p
WHERE Row BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1;
答案 2 :(得分:1)
您可以使用CTE
;
;With CTE as
(
SELECT PostId, Message, (ROW_NUMBER() OVER (ORDER BY LastUpdateDateTime DESC)) as Row
FROM Posts
WHERE Posts.TimePointId=@TimePointId AND IsFixed=0
ORDER BY LastUpdateDateTime DESC
)SELECT Row,* FROM CTE
WHERE Row BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1