【发布时间】:2010-10-08 15:21:59
【问题描述】:
您正在为线程讨论板创建数据库架构。有没有一种有效的方法来为给定线程选择正确排序的列表?我编写的代码有效,但也没有按照我想要的方式排序。
假设您有以下数据:
ID |父母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 数据类型。在阅读了this comment 的相关信息后,我决定将其纳入我的设计中。今晚我将对此进行试验,如果我成功了,我会发布更多信息。
更新
使用 dance2die 的建议从我的样本数据返回结果:
ID |家长 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
【问题讨论】:
-
sql 之神对你的说法感到愤怒
标签: sql linq tsql recursion common-table-expression