【问题标题】:Sorting comments with nested replies使用嵌套回复对评论进行排序
【发布时间】:2012-04-09 16:28:26
【问题描述】:

我正在尝试提出一个查询,该查询将在他们的回复及其回复之后返回 cmets。

有点像

comment 1
reply 1.1
reply 1.1.1
reply 1.2
comment 2
comment 3
comment 3.1 

到目前为止我有这个

SELECT [CommentID]
  ,[ParentID]
  ,[Message]
  , ROW_NUMBER() over(partition by ParentID order by CommentID ) as rn
  ,[CreatedBy]
  ,[CreatedDate]
  FROM [DBNAME].[dbo].[Commenttable] 
  GROUP BY [CommentID],[ParentID],[CreatedDate],[Message],[CreatedBy]

但我得到的是

comment 1
comment 2
comment 3
reply 1.1
reply 1.2
reply 3.1
reply 1.1.1

基本结构只是一个包含评论 ID、父 ID 和消息的表格。 cmets 和回复只是为了帮助解释我想要实现的目标

【问题讨论】:

  • 可以通过您的结构和缺乏细节来说明很多问题,但请尝试在您的 group by 之后添加 ORDER BY ParentID、CommentID 子句
  • 尝试按结果集中的第二列排序。
  • 使您的所有版本号一致...即。 1.0.0、2.0.0 而不是 1 和 2。或者将它们拆分为单独的字段。版本号、颠覆号等
  • 如果您无法更改架构...创建函数以提取版本号的这些组件。 (暂时不用担心使用函数对性能的影响)
  • @samyi:那些“版本号”可能只是为了表明哪个评论是对其他评论的回应,以便我们可以看到它们应该如何排序。我的意思是,也许它们只适合我们。它们不一定以这种形式出现在表格中。即使它们是,您也不应该期望有一个明确的最大嵌套级别。我的意思是,可能会有 10 个级别的回复,或者根本没有回复,您只是不知道要附加多少 .0s(没有先“预览”表格,这可能意味着双重工作)。

标签: sql tsql


【解决方案1】:

试试这个:

declare @CommentTable as Table ( CommentId Int Identity, ParentId Int Null, Message VarChar(16) )
insert into @CommentTable ( ParentId, Message ) values
  ( null, '1' ),
  ( null, '2' ), ( 1, '1.1' ),
  ( null, '3' ), ( 4, '3.1' ), ( 3, '1.1.1' ), ( 1, '1.2' )
select * from @CommentTable

; with Cindy as (
  -- Start with the base comments.
  select CommentId, ParentId, Message, Row_Number() over ( order by CommentId ) as Number,
    Cast( Row_Number() over ( order by CommentId ) as VarChar(1000) ) as Path,
    Cast( Right( '0000' + Cast( Row_Number() over ( order by CommentId ) as VarChar(4) ), 5 ) as VarChar(1000) ) as OrderPath
    from @CommentTable
    where ParentId is NULL
  union all
  -- Add replies on layer at a time.
  select CT.CommentId, CT.ParentId, CT.Message, Row_Number() over ( order by CT.CommentId ),
    Cast( C.Path + '.' + Cast( Row_Number() over ( order by CT.CommentId ) as VarChar(4) ) as VarChar(1000) ),
    Cast( C.OrderPath + Right( '0000' + Cast( Row_Number() over ( order by CT.CommentId ) as VarChar(4) ), 5 ) as VarChar(1000) )
    from @CommentTable as CT inner join
      Cindy as C on C.CommentId = CT.ParentId
  )
  select *
    from Cindy
    order by OrderPath

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-17
    • 2013-03-10
    • 1970-01-01
    • 2021-07-24
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多