日期:2014-05-18  浏览次数:20620 次

同一条sql语句内有两个相同的子查询,有没有什么好方法优化下???
如题:

sql语句如下:
SQL code

select top 15 * from ( select * from table where sid=1004 ) as M 
 where id > (select max (id) 
               from (select top (15 * (20 - 1)) id 
                       from ( select * from table where sid=1004 ) as M
                      where order by id 
                    ) as T 
             ) order by id



就是一个旧系统中的分页语句,
想稍微优化下,
想到用表变量,
但觉得好麻烦,
希望各位给出更好的方法

------解决方案--------------------
为什么不分开来写呢?

select * into #a from table where sid=1004 
select top (15 * (20 - 1)) id itno #b from #a where order by id 
select top 15 * from #a where id > (select max (id) from #b ) order by id

------解决方案--------------------
--修正一下,刚才变量写返了
SQL code

declare @pagesize int 
set @pagesize=15 --每页15条
declare @pageindex int 
set @pageindex=2 --第20页

;with maco as
(
    select row_number() over (order by id) as num,* from [table] where sid=1004
)

select * from maco 
where num between (@pagesize*(@pageindex-1)+1) and @pageindex*@pagesize