图像您正在为线程化讨论板创建数据库模式。有没有一种有效的方法来为给定线程选择正确排序的列表?我编写的代码有效,但也没有按照我想要的方式排序。
假设您有以下数据:
身份证 | 父母ID ----------------- 1 | 无效的 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
任何帮助,将不胜感激; 谢谢!
我是 SQL 新手,之前没有听说过 hierarchyid 数据类型。在从这个评论中阅读它之后,我决定我可能想要将它纳入我的设计中。今晚我将对此进行试验,如果成功,我会发布更多信息。
使用 dance2die 的建议更新从我的示例数据返回的结果:
身份证 | 家长 ID | 水平 | 密集等级 ------------------------------------- 15 空 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