我还需要有关分页和UNION ALL
用于多个表的帮助:
UNION ALL
在使用并仅返回特定行数来连接多个表时,如何实现优化的分页...
declare @startRow int
declare @PageCount int
set @startRow = 0
set @PageCount = 20
set rowcount @PageCount
select Row_Number() OVER(Order by col1) as RowNumber, col1, col2
from
(
select col1, col2 from table1 where datetimeCol between (@dateFrom and @dateTo)
union all
select col1, col2 from table2 where datetimeCol between (@dateFrom and @dateTo)
union all
select col1, col2 from table3 where datetimeCol between (@dateFrom and @dateTo)
union all
select col1, col2 from table4 where datetimeCol between (@dateFrom and @dateTo)
union all
select col1, col2 from table5 where datetimeCol between (@dateFrom and @dateTo)
) as tmpTable
where RowNumber > @startRow
表 3、4 和 5 有大量行(数百万行),而表 1 和 2 可能只有几千行。
如果 startRow 为“0”,我只期望第 1 行到第 20 行的数据(来自表 1)。我得到了正确的结果,但是在 sql server 尝试所有数据并对其进行过滤时,剩余表的开销很高。
@dateFrom 和 @dateTo 的间隔越长,在尝试从整个结果集中仅检索几行时,我的查询就会显着变慢
请帮助我如何用类似的逻辑实现一个简单但更好的方法。:(