Bil*_*tes 9 sql t-sql linq recursion common-table-expression
您正在为线程化讨论板创建数据库架构的映像.有没有一种有效的方法为给定的线程选择正确排序的列表?我写的代码有效,但不按照我想要的方式排序.
假设你有这些数据:
ID | ParentID ----------------- 1 | null 2 | 1 3 | 2 4 | 1 5 | 3
所以结构应该是这样的:
1 |- 2 | |- 3 | | |- 5 |- 4
理想的情况是,在代码中,我们想要的结果集出现在以下顺序:1,2,3,5,4
问题:随着CTE我写的实际上是被返回为:1,2,4,3,5
我知道使用LINQ可以很容易地进行分组/排序,但我不愿意在内存中这样做.这似乎是目前最好的解决方案......
这是我目前正在使用的CTE:
with Replies as (
select c.CommentID, c.ParentCommentID 1 as Level
from Comment c
where ParentCommentID is null and CommentID = @ParentCommentID
union all
select c.CommentID, c.ParentCommentID, r.Level + 1 as Level
from Comment c
inner join Replies r on c.ParentCommentID = r.CommentID
)
select * from Replies
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激; 谢谢!
ID | ParentID | Level | DenseRank ------------------------------------- 15 NULL 1 1 20 15 2 1 21 20 3 1 17 22 3 1 22 15 2 2 31 15 2 3 32 15 2 4 33 15 2 5 34 15 2 6 35 15 2 7 36 15 2 8
我相信你一定会喜欢这个.我最近发现了Dense_Rank()函数,它用于根据MSDN "在结果集的分区内排名"
查看下面的代码以及"CommentID"的排序方式.
据我所知,您正在尝试通过ParentCommentID对结果集进行分区.
注意"denserank"栏目.
with Replies (CommentID, ParentCommentID, Level) as
(
select c.CommentID, c.ParentCommentID, 1 as Level
from Comment c
where ParentCommentID is null and CommentID = 1
union all
select c.CommentID, c.ParentCommentID, r.Level + 1 as Level
from Comment c
inner join Replies r on c.ParentCommentID = r.CommentID
)
select *,
denserank = dense_rank() over (partition by ParentCommentID order by CommentID)
from Replies
order by denserank
Run Code Online (Sandbox Code Playgroud)

结果如下
嗯 - 我不确定你的结构是否最适合这个问题。在我的脑海中,无论如何我都想不出如何在上面的查询中按照您想要的方式对数据进行排序。
我能想到的最好的办法是,如果您有一个将您的评论联系在一起的父表(例如主题表)。如果您这样做,您应该能够简单地将您的回复加入到该回复中(显然您需要包含正确的列),然后您可以按主题ID、级别进行排序以获得您想要的排序顺序(或有关的任何其他信息)主题表代表了很好的排序价值)。
| 归档时间: |
|
| 查看次数: |
4493 次 |
| 最近记录: |