• 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.ContentInfoCode
    FROM [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-按照递归查询格式创建递归查询:

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

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

    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   --删除临时表
  • 相关阅读:
    python 三行代码实现快速排序
    kafka使用自带zookeeper 单机版安装、配置、启动、生产消费消息测试
    kafka manager添加集群出现错误KeeperErrorCode
    常用的kubectl命令
    20210531-20210606 助教一周小结(第十八周)
    20210524-20210530 助教一周小结(第十七周)
    20210517-20210523 助教一周小结(第十六周)
    20210510-20210516 助教一周小结(第十五周)
    20210503-20210509 助教一周小结(第十四周)
    20210426-20210502 助教一周小结(第十三周)
  • 原文地址:https://www.cnblogs.com/lxhbky/p/5730093.html
Copyright © 2020-2023  润新知