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

sql 查询语句。解决思路

2013-10-21 
sql 查询语句。CREATE TABLE [ExpertReply]([ID] [int] NOT NULL,[UserID] [int] NOT NULL,[BlogID] [int]

sql 查询语句。


CREATE TABLE [ExpertReply](
    [ID] [int] NOT NULL,
    [UserID] [int] NOT NULL,
    [BlogID] [int] NOT NULL,
    [CommentID] [int] NOT NULL,
    [Context] [nvarchar](max) NULL,
    [CreateTime] [datetime] NOT NULL,
)
 

 
insert ExpertReply values(1, 1, 1, 0, '回复1', GETDATE())
insert ExpertReply values(2, 2, 1, 0, '回复2', GETDATE())
insert ExpertReply values(3, 3, 1, 0, '回复3',  GETDATE())
insert ExpertReply values(4, 4, 1, 2, '评论1',  GETDATE())
insert ExpertReply values(5, 3, 1, 3, '评论3',  GETDATE())
insert ExpertReply values(6, 2, 1, 2, '评论2',  GETDATE())
insert ExpertReply values(7, 3, 1, 3, '评论4',  GETDATE())

想要的效果是:如果这条回复有评论,那么下一条数据就是他的评论
例如:
回复1
回复2
评论1
评论2
回复3
评论3
评论4
回复4
.....

下面的这条语句效果不太理想,有朋友能帮忙修改,或者提出更好的方法么?

select * from ExpertReply order by case when CommentID!=0 then CommentID else id end
[解决办法]

with tb as(select id,commentid=id,context from  [ExpertReply] where  commentid=0
union all
select  a.id,tb.commentid,a.context   from tb,[ExpertReply] a where tb.id=a.commentid
)
select context from tb
order by commentid,id


这样OK吗?
[解决办法]
--CREATE TABLE [ExpertReply]( 
--    [ID] [int] NOT NULL, 
--    [UserID] [int] NOT NULL, 
--    [BlogID] [int] NOT NULL, 
--    [CommentID] [int] NOT NULL, 
--    [Context] [nvarchar](max) NULL, 
--    [CreateTime] [datetime] NOT NULL, 
--) 
   
  
   
--insert ExpertReply values(1, 1, 1, 0, '回复1', GETDATE()) 
--insert ExpertReply values(2, 2, 1, 0, '回复2', GETDATE()) 
--insert ExpertReply values(3, 3, 1, 0, '回复3',  GETDATE()) 
--insert ExpertReply values(4, 4, 1, 2, '评论1',  GETDATE()) 
--insert ExpertReply values(5, 3, 1, 3, '评论3',  GETDATE()) 
--insert ExpertReply values(6, 2, 1, 2, '评论2',  GETDATE()) 
----insert ExpertReply values(7, 3, 1, 3, '评论4',  GETDATE())
;WITH cte AS (


SELECT id,CommentID,context,id AS parentid
FROM ExpertReply
WHERE CommentID=0
UNION ALL 
SELECT a.id,a.commentid,a.context,b.id AS parentid
FROM ExpertReply a INNER JOIN cte b ON a.CommentID=b.id
)
SELECT id,CommentID,context FROM cte
ORDER BY parentid

/*
id          CommentID   context
----------- ----------- ----------------------------------------------------------------------------------------------------------------
1           0           回复1
2           0           回复2
4           2           评论1
6           2           评论2
3           0           回复3
5           3           评论3
7           3           评论4

*/

热点排行