我正在使用sql server 2008 r2并且具有以下查询
select * from
(
select d.ID as ID,
....
....
ROW_NUMBER() OVER
(
ORDER BY #some field
) AS RowNum
from
/*some table*/
LEFT join
(select Device_ID,
Level,
ROW_NUMBER() over (partition by Device_ID order by id desc) as rn
from #sometable as de WITH (NOLOCK)
where #some condition
) t
where t.rn = 1)tmp on ID=tmp.Device_ID **/* sort operation 1*/**
/*some more joins */
WHERE /*some condition*/
) as DbD
where RowNum BETWEEN @SkipRowsLocal and (@SkipRowsLocal + @TakeRowsLocal - 1)
order by RowNum
我正在尝试从示例中实现分页类型的查询 http://blog.sqlauthority.com/2013/04/14/sql-server-tricks-for-row-offset-and-paging-in-various-versions-of-sql-server/
但看起来它的执行速度很慢,当我查看查询计划排序操作消耗了近50%的查询时间时,我猜它是我标记为1的第一个排序操作,基本上在临时表中我想要检索我想获取的最新值和外行数只能说40条记录。
它基本上就像排序10K行然后从中排出40行,我们有什么办法可以改进这个查询吗?
答案 0 :(得分:0)
而不是左连接,尝试OUTER APPLY,以获得您感兴趣的设备的TOP 1 - 将其视为'我从第一个表中获取记录,然后为该记录,我去另一个表中获取该设备ID的TOP 1,但记住在第二个表中,您需要搜索第一个表中的数据,而不是连接
select * from
(
select d.ID as ID,
....
....
ROW_NUMBER() OVER
(
ORDER BY #some field
) AS RowNum
from
/*some table*/
OUTER APPLY
(select TOP 1 Device_ID,
Level
from #sometable as de WITH (NOLOCK)
where #some condition and Device_ID = [/*some table*/].id ORDER BY id DESC
) t
)tmp
/*some more joins */
WHERE /*some condition*/
) as DbD
where RowNum BETWEEN @SkipRowsLocal and (@SkipRowsLocal + @TakeRowsLocal - 1)
order by RowNum
在这些行上的某些内容,您可能只想构建查询的相关部分并进行比较,它似乎会避免排序并且索引可能很快