使用一个SQL表进行三向联接

| 假设有一个MSSQL表UserPost,它代表用户已发布的内容,并具有以下字段:
ID | dateAdded | parentPostID |  postBody
系统中的用户可以创建一个请求,接收一个响应,然后其他用户可以对该响应进行评论。即,请求<= 1:许多=>响应<= 1:许多=>注释(请考虑StackOverlow的问题>答案>类似于注释模型)。 所有用户帖子(请求,响应和评论)均由UserPost行表示,其中Request为1;响应的“ 2”是请求的ID,注释的“ 2”是响应的ID。 我需要以一种简单的方式输出所有内容:
Request 1
- Response A
-- Comment (i)
-- Comment (ii)
- Response B
-- Comment (i)
Request 2
...
问题:哪个SQL语句以最有用的方式返回所需的信息? 我正在努力在(UserPosts)作为请求[join](UserPosts)作为响应[join](UsersPosts)作为Comment之间编写三向联接,但不确定这是最简单的方法。 奖励:是否可以使用C#Linq做到这一点?     
已邀请:

bab

想不到在LINQ中做到这一点的方法。我已经删除了未使用的列。幸运的是,这是一个有限的层次结构。我正在使用新的
hierarchyid
数据类型,该数据类型具有所需的排序顺序:
create table UserPosts (
    ID int not null,
    ParentID int null
)
go
insert into UserPosts (ID,ParentID)
select 1,null union all
select 2,null union all
select 3,1 union all
select 4,2 union all
select 5,3 union all
select 6,1 union all
select 7,6
go
select
    *
from
    UserPosts up
        left join
    UserPosts up_1st
        on
            up.ParentID = up_1st.ID
        left join
    UserPosts up_2nd
        on
            up_1st.ParentID = up_2nd.ID
order by
    CONVERT(hierarchyid,
    COALESCE(\'/\' + CONVERT(varchar(10),up_2nd.ID),\'\') +
    COALESCE(\'/\' + CONVERT(varchar(10),up_1st.ID),\'\') +
    \'/\' + CONVERT(varchar(10),up.ID) + \'/\'
    )
HierarchyID(作为字符串)看起来像
/GrandParent/Parent/Child/
-因此我们构造的值看起来像这样。显然,如果我们没有祖父母(
up_2nd.ID
为空,因为我们无法实现所描述的2个左连接),那么我们只想构造ѭ9this-这就是第一个COALESCE正在帮助我们实现的目标。同样,如果找不到任何父母(
up_1st.ID
up_2nd.ID
均为空),则两个COALESCE都变成空字符串,最终构成
/ID/
。 你可以加:
CASE
    WHEN up_2nd.ID is not null then \'Comment\'
    WHEN up_1st.ID is not null then \'Response\'
    ELSE \'Request\'
END as Level
如果要跟踪项目的级别,请转到选择列表(或根据需要使用数字)     

要回复问题请先登录注册