现在假设我要取第10行至15行的数据,我的做法如下:
select top 6 *
from tblMaterial
where MatID not in(
select top 9 MatID
from tblMaterial
)
因为使用了"not in",所以当数据量大的时候,查询非常慢。
比如现在我想取第5000行到5005,此时的速度就比查询第10行到15行的速度慢多了。
8 个解决方案
#1
采用视图试
#2
select top 6
from (
select top 15 *
from tblMaterial
order by MatID)
order by MatID desc
#3
假设表中有唯一ID字段:
--第11条到第30条,共选出20条记录
select *
from (select top 20 * from (select top 30 * from 表名 order by ID) t1 order by ID desc) t2
order by ID
--或
--第11条到第30条,共选出20条记录
select top 20 *
from 表名
where ID>(select max(ID) from (select top 10 ID from 表名 order by ID) t1)
order by ID
#4
--第10到15行,共6条数据
select top 6 *
from
(
select top 15 *
from tblMaterial
order by MatID
) as t
order by MatID desc
select top 6 *
from
(
select top 15 *
from tblMaterial
order by MatID
) as t
order by MatID desc
#5
--第10到15行,共6条数据
select top 6 *
from
(
select top 15 *
from tblMaterial
order by MatID
) as t
order by MatID desc
--第5000到5005行,共6条数据
select top 6 *
from
(
select top 5005 *
from tblMaterial
order by MatID
) as t
order by MatID desc
#6
用SELECT TOP解决,前提是MatID唯一标记,且从小->大顺序
select top 6 *
from (select top 5005 * from tblMaterial order by MatID ) order by MatID desc
select top 6 *
from (select top 5005 * from tblMaterial order by MatID ) order by MatID desc
#7
这样的需求最好有唯一字段,如:ID
#8
with total as
(select *, row_number() over(order by Id) as rowNum from users)
select * from total where rowNum between 5000 and 5015
(select *, row_number() over(order by Id) as rowNum from users)
select * from total where rowNum between 5000 and 5015
#1
采用视图试
#2
select top 6
from (
select top 15 *
from tblMaterial
order by MatID)
order by MatID desc
#3
假设表中有唯一ID字段:
--第11条到第30条,共选出20条记录
select *
from (select top 20 * from (select top 30 * from 表名 order by ID) t1 order by ID desc) t2
order by ID
--或
--第11条到第30条,共选出20条记录
select top 20 *
from 表名
where ID>(select max(ID) from (select top 10 ID from 表名 order by ID) t1)
order by ID
#4
--第10到15行,共6条数据
select top 6 *
from
(
select top 15 *
from tblMaterial
order by MatID
) as t
order by MatID desc
select top 6 *
from
(
select top 15 *
from tblMaterial
order by MatID
) as t
order by MatID desc
#5
--第10到15行,共6条数据
select top 6 *
from
(
select top 15 *
from tblMaterial
order by MatID
) as t
order by MatID desc
--第5000到5005行,共6条数据
select top 6 *
from
(
select top 5005 *
from tblMaterial
order by MatID
) as t
order by MatID desc
#6
用SELECT TOP解决,前提是MatID唯一标记,且从小->大顺序
select top 6 *
from (select top 5005 * from tblMaterial order by MatID ) order by MatID desc
select top 6 *
from (select top 5005 * from tblMaterial order by MatID ) order by MatID desc
#7
这样的需求最好有唯一字段,如:ID
#8
with total as
(select *, row_number() over(order by Id) as rowNum from users)
select * from total where rowNum between 5000 and 5015
(select *, row_number() over(order by Id) as rowNum from users)
select * from total where rowNum between 5000 and 5015