分页查询写法性能比较
写法1:
with T as(select *, ROW_NUMBER() over(order by ID desc) nr
from Table1 where 1=1 and CreateTime >='2020-02-28 09:00:19' and CreateTime <='2020-05-28 09:00:19')
select * from T where nr between ((2 - 1) * 20 + 1) and (2 * 20)
写法2:
with T as(SELECT * FROM (SELECT ID, ROW_NUMBER() over(order by ID desc) nr FROM Table1
where 1=1 and CreateTime >='2020-02-28 09:00:19' and CreateTime <='2020-05-28 09:00:19') A
WHERE nr between ((2 - 1) * 20 + 1) and (2 * 20)) select V.* from T INNER JOIN Table1 V ON T.ID=V.ID
写法3:
SELECT * INTO #T FROM (SELECT ID, ROW_NUMBER() over(order by ID desc) nr FROM Table1 where 1=1 and CreateTime >='2020-02-28 09:00:19' and CreateTime <='2020-05-28 09:00:19') A
WHERE nr between ((2 - 1) * 20 + 1) and (2 * 20) select V.* from #T INNER JOIN Table1 V ON #T.ID=V.ID
结论:
在我工作中遇到的场景中,写法1用时6s,写法2用时2s,写法3用时不到1s