在我的个人资料网站上,用户可以发表评论,并对评论发表评论(就像 facebook 的 1 级)。我正在实现一些分页,因为 1 个个人资料可以有数千条评论。分页有效,但是,由于有子评论,一个简单的前 n 查询会中断对话。我只想对父注释进行分页,而不是对子注释进行分页。
表'评论' 其中有:
- commentID
- commentText
- parentCommentID
- commentOnUserID
这里的问题是我只想对父评论 (parentCommentID = 0) 进行分页。所以我写了一个查询:
select * from Comments c
where c.parentCommentID = 0
and c.commentOnUserID = 65939
(我省略了实际的分页查询,因为它不相关)
但我还想加载所有这些评论的子项,子项也是一个评论,但随后 parentCommentID = some commentID:
select * from comments c
where c.parentCommentID in ( * get the commentId's from the previous query)
and c.commentOnUserID = 65939
有没有一种方法可以有效地将两者合二为一的查询?
最佳答案
declare @T table(commentID int,
commentText varchar(max),
parentCommentID int,
commentOnUserID int)
insert into @T values
(1, 'Comment 1', 0, 1),
(2, 'Comment 2', 0, 1),
(3, 'Comment 3', 0, 1),
(4, 'Comment 4 sub 1', 1, 1),
(5, 'Comment 5 sub 1', 1, 1),
(6, 'Comment 6 sub 1', 1, 1),
(7, 'Comment 1 sub 2', 2, 1),
(8, 'Comment 1 sub 2', 2, 1),
(9, 'Comment 1 sub 3', 3, 1)
declare @UserID int = 1
;with cte as
(
select
T.commentID,
T.CommentText,
row_number() over(order by commentID) as rn
from @T as T
where
T.parentCommentID = 0 and
T.commentOnUserID = @UserID
union all
select
T.commentID,
T.CommentText,
C.rn
from @T as T
inner join cte as C
on T.parentCommentID = C.commentID
)
select *
from cte
where rn between 1 and 2 -- use rn for pagination
order by rn, commentID
结果
commentID parentCommentID CommentText rn
----------- --------------- -------------------- --------------------
1 0 Comment 1 1
4 1 Comment 4 sub 1 1
5 1 Comment 5 sub 1 1
6 1 Comment 6 sub 1 1
2 0 Comment 2 2
7 2 Comment 1 sub 2 2
8 2 Comment 1 sub 2 2
关于sql-server - 如何更有效地编写此查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5688058/