你的位置:首页 > 数据库

[数据库]SQL_递归查询(复杂查询示例)


本博客为原创博客,转载请注明地址及作者,谢谢!

需求: 一篇文章里有很多评论,每个评论又有很多回复评论,要求: 页面将文章展示出来,且文章的主评论按照评论时间分页展示,回复评论的评论完全展示在每个主评论下面,且按照回复时间排序

最终查询结果SQL查询结果如下:

Code: 评论编码,ParentCode:回复评论编码,num:主评论序号,lvl:评论层级,CreateTime:评论创建时间

 

SQL详细过程如下: 

1-先创建我们的数据临时表作为基础数据:

a.ContentInfoCode为文章编码
SELECT * INTO #a FROM (SELECT A.LikeNum, F.Title AS ContentTitle,A.CommentNum,A.ValidStatus, A.Code, E.CommentInfo as ReplayCommentInfo,A.CommentInfo,A.ParentCode, A.CreateTime ,B.LogoImageUrl ,( CASE WHEN D.Code IS NULL then '0' else '1' end) as IsLike ,C.LoginName,C.UserName,G.LoginName AS ReplyLoginName,G.UserName as ReplyUserName,f.ValidStatus as ContentValidStatus,a.ContentInfoCodeFROM [Content].Comment A LEFT JOIN [OAuth].[UserHeadPhoto] B ON A.Creator=B.UserID and B.[VersionEndTime]='9999-12-31 23:59:59' LEFT JOIN [OAuth].[UserInfo] C ON (A.Creator=C.UserID and c.Status=1 ) left join [Content].[UserAction] D ON (A.Code=D.CommentCode AND D.ActionType=1 AND D.Creator='b231f35a76a346449b2f4c5ddb4f88e7' )  left Join [Content].Comment E ON A.ParentCode=E.Code left join [Content].[ContentInfo] F on a.ContentInfoCode =f.code left join [OAuth].[UserInfo] G ON (E.Creator=G.UserID and G.Status=1 ) WHERE 1=1 and a.ContentInfoCode='042f89bea6ee40f4968d2a219352f2f8') A 

2-按照递归查询格式创建递归查询:

with cte as(  SELECT * FROM (  select *,0 as lvl,ROW_NUMBER() over(order by CreateTime desc ) num from #a   WHERE ParentCode IS NULL   ) B WHERE B.num BETWEEN 1 AND 20 --主评论集合  union all  select #a.*,c.lvl+1,c.num   --子评论要展示的列(lvl层级列,按照c.Code=#a.ParentCode每层级+1,子评论num列直接使用主评论序号)  from cte c   inner join #a on c.Code = #a.ParentCode --主评论和子评论关系)select * from cte ORDER BY num,CreateTime DESC --查询最终结果_按照主评论序号和创建时间排序

 3-查询结果,并删除临时表:

select * from cte ORDER BY num,CreateTime DESC  --主评论和子评论关系
DROP TABLE #a  --删除临时表