SQL_递归查询(复杂查询示例)

前端之家收集整理的这篇文章主要介绍了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 1end) as IsLike,C.LoginName,C.UserName,G.LoginName AS ReplyLoginName,G.UserName as ReplyUserName,f.ValidStatus as ContentValidStatus,a.ContentInfoCode
FROM [Content].Comment A LEFT JOIN OAuth].UserHeadPhoto] B ON  A.Creator=B.UserID and B.VersionEndTime]=9999-12-31 23:59:59'
 UserInfo] C ON (A.Creator=C.UserID and c.Status=1 )
  left join UserAction] D ON (A.Code=D.CommentCode AND D.ActionType1 AND D.Creatorb231f35a76a346449b2f4c5ddb4f88e7' ) 
  Join ].Comment E ON A.ParentCode=E.Code ContentInfo] F on a.ContentInfoCode =f.code  ] G ON (E.Creator=G.UserID and G.Status )
 WHERE 11  and a.ContentInfoCode042f89bea6ee40f4968d2a219352f2f8
) A 

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

评论集合--根数据--涉及表名:cte c,需要增加过滤条件:ParentCode IS NULL

评论集合--子数据--涉及表名:#a,不加条件

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

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

DESC   --主评论和子评论关系
DROP TABLE #a   --删除临时表

 

猜你在找的MySQL相关文章