首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

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

2012-03-12 
同一条sql语句内有两个相同的子查询,有没有什么好方法优化下???如题:sql语句如下:SQL codeselect top 15 *

同一条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 

热点排行