+ -
当前位置:首页 → 问答吧 → 怎么实现这样的查询?

怎么实现这样的查询?

时间:2011-12-03

来源:互联网

---------------
表comment:
id:为子编号
pid:为自编号(不是子节点的话pid为0)
subdate:为时间
id pid subdate
1 0 2011-11-1 12:01:01
2 0 2011-11-1 12:02:01
3 0 2011-11-1 12:03:01
4 1 2011-11-1 12:04:01
5 3 2011-11-1 12:04:07
6 0 2011-11-1 12:04:08
7 5 2011-11-1 12:04:09
---------------
想实现的目标:
按照时间的倒序查询出树形记录:
id pid subdate
6 0 2011-11-1 12:04:08
3 0 2011-11-1 12:03:01
5 3 2011-11-1 12:04:07
7 5 2011-11-1 12:04:09
2 0 2011-11-1 12:02:01
1 0 2011-11-1 12:01:01
4 1 2011-11-1 12:04:01
---------------
用asp怎么实现啊?

作者: xzb_97   发布时间: 2011-12-03

使用递归查询即可

作者: chinmo   发布时间: 2011-12-03

SQL code

select id,pid,subdate from comment order by subdate desc

作者: p2227   发布时间: 2011-12-03

另外,你主楼的id为4的记录跟你描述的不符

作者: p2227   发布时间: 2011-12-03

引用 2 楼 p2227 的回复:
SQL code

select id,pid,subdate from comment order by subdate desc

谢谢,我没说全,是评论的倒序时间来查询,评论还有子评论,所以不知道该怎么弄。

作者: xzb_97   发布时间: 2011-12-03

如果在SQL 2005里,可用递归处理:
SQL code
create table comment(id int,pid int,subdate datetime)
insert into comment select 1,0,'2011-11-1 12:01:01'
insert into comment select 2,0,'2011-11-1 12:02:01'
insert into comment select 3,0,'2011-11-1 12:03:01'
insert into comment select 4,1,'2011-11-1 12:04:01'
insert into comment select 5,3,'2011-11-1 12:04:07'
insert into comment select 6,0,'2011-11-1 12:04:08'
insert into comment select 7,5,'2011-11-1 12:04:09'
go
;with cte as(
select convert(decimal(10,5),ROW_NUMBER()over(order by subdate desc))rn,convert(decimal(10,5),1) as flg,* from comment where pid=0
union all
select convert(decimal(10,5),ROW_NUMBER()over(order by b.subdate desc)*a.flg/10+a.rn),convert(decimal(10,5),a.flg/10),b.* from cte a inner join comment b on a.id=b.pid
)select id,pid,subdate  from cte order by rn
/*
id          pid         subdate
----------- ----------- -----------------------
6           0           2011-11-01 12:04:08.000
3           0           2011-11-01 12:03:01.000
5           3           2011-11-01 12:04:07.000
7           5           2011-11-01 12:04:09.000
2           0           2011-11-01 12:02:01.000
1           0           2011-11-01 12:01:01.000
4           1           2011-11-01 12:04:01.000

(7 行受影响)

*/
go
drop table comment

作者: qianjin036a   发布时间: 2011-12-03

引用 3 楼 p2227 的回复:
另外,你主楼的id为4的记录跟你描述的不符

是按照评论pid=0的subdate来倒序,然后还有pid不为0的,那么就以id=pid的记录按时间倒序排列,所以id=4的记录在最后。

作者: xzb_97   发布时间: 2011-12-03

引用 5 楼 qianjin036a 的回复:
如果在SQL 2005里,可用递归处理:

SQL code
create table comment(id int,pid int,subdate datetime)
insert into comment select 1,0,'2011-11-1 12:01:01'
insert into comment select 2,0,'2011-11-1 12:02:01'
inser……

谢谢,数据库环境是在access2003里,所以2005只好放弃了。

作者: xzb_97   发布时间: 2011-12-03

引用 1 楼 chinmo 的回复:
使用递归查询即可

能给个例子吗?

作者: xzb_97   发布时间: 2011-12-04