当前位置: 代码迷 >> Sql Server >> sql分页查询解决思路
  详细解决方案

sql分页查询解决思路

热度:93   发布时间:2016-04-24 19:50:35.0
sql分页查询
数据如下

ID HasChild Lev
1    0       1
2    0       1
3    2       2
4    2       2
5    3       3
6    0       1
7    0       1
8    0       1
9    0       1
10   0       1
11   10      2
12   0       1
13   12      2
14   0       1
15   14      2

这是一个树形结构 我的需求是每页显示五条,但是这五条必须包括根节点和子节点 
分页效果如下
第一页:
1    0       1
2    0       1
3    2       2
4    2       2
5    3       3
6    0       1
7    0       1
8    0       1
第二页
9    0       1
10   0       1
11   10      2
12   0       1
13   12      2
14   0       1
15   14      2
sql? 分页查询

------解决方案--------------------

select 1 ID ,0 HasChild ,1 Lev
into #temp
union all select 2  ,0  ,1
union all select 3  ,2  ,2
union all select 4  ,2  ,2
union all select 5  ,3  ,3
union all select 6  ,0  ,1
union all select 7  ,0  ,1
union all select 8  ,0  ,1
union all select 9  ,0  ,1
union all select 10 ,0  ,1
union all select 11 ,10 ,2
union all select 12 ,0  ,1
union all select 13 ,12 ,2
union all select 14 ,0  ,1
union all select 15 ,14 ,2

declare @pagenum int=1;
declare @pagerownum int=5;

with t as
(
select  id
from 
(
select top (@pagerownum*@pagenum) *,ROW_NUMBER() over(order by id) rn
from #temp
where lev=1
) t
where rn>@pagerownum*(@pagenum-1)
)
select *
from #temp
where id in(select id from t)
or haschild in (select id from t)

------解决方案--------------------
引用:
Quote: 引用:

你的分页效果里面,第一页显示的是8行,第二页7行。你的需求是每页显示五条。这个怎么理解呢


就是说每一页显示5行根节点的数据 但是必须把子节点也查出来绑定在控件上 那样显示出来就是五行 把节点打开就是5+行了


这个根节点是lev为1的嘛,而子节点是否是这5个根节点的子节点呢
------解决方案--------------------

create table q10
(ID int,HasChild int,Lev int)

insert into q10
 select 1, 0, 1 union all
 select 2, 0, 1 union all
 select 3, 2, 2 union all
 select 4, 2, 2 union all
 select 5, 3, 3 union all
 select 6, 0, 1 union all
 select 7, 0, 1 union all
 select 8, 0, 1 union all
 select 9, 0, 1 union all
 select 10, 0, 1 union all
 select 11, 10, 2 union all
 select 12, 0, 1 union all
 select 13, 12, 2 union all
 select 14, 0, 1 union all
 select 15, 14, 2
 
 
-- test1
  相关解决方案