当前位置: 代码迷 >> Sql Server >> 同一条sql语句内有两个相同的子查询,有没有什么好方法优化下?解决方案
  详细解决方案

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

热度:62   发布时间:2016-04-27 14:28:51.0
同一条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 @[email protected]
  相关解决方案