SQL Parent/Child CTE Ordering

后端 未结 2 1547
走了就别回头了
走了就别回头了 2021-01-22 10:29

I\'m trying to create a forum setup where you can comment on specific posts and have the replies show immediately below the parent in date order. There will only be one sub-lev

相关标签:
2条回答
  • 2021-01-22 11:23

    For a single level depth, you don't need to use recursion - try:

    SELECT ID, ParentID, Datestamp
    FROM ForumMessages
    order by coalesce(ParentID,ID), Datestamp
    
    0 讨论(0)
  • 2021-01-22 11:30

    Very easy way without CTE (ISNULL is the function in MSSQL but you don't give the RDBMS):

    SELECT ID, ParentID, Datestamp
    
    FROM ForumMessages
    
    ORDER BY ISNULL(ParentID,ID), DateStamp
    

    Fiddle

    0 讨论(0)
提交回复
热议问题