SQL - 分页评论

时间:2015-05-19 07:29:12

标签: sql sql-server sql-server-2008 comments paging

我有下面的表评论:

CREATE TABLE Comment
(
     CommentID int,
     Username nvarchar(50),
     Content nvarchar(255),
     ReplyID int,
     primary key (CommentID),
)

ALTER TABLE dbo.Comment
ADD FOREIGN KEY (CommentID) REFERENCES dbo.Comment (CommentID) ON DELETE NO ACTION ON UPDATE NO ACTION,

我想用详细信息查询详细产品中的分页评论:

+----+----------+-------------+---------+
| ID | Username |   Content   | ReplyID |
+----+----------+-------------+---------+
|  1 | UserA    | hello       | null    |
|  2 | UserB    | hello       | null    |
|  3 | UserC    | Hi UserA    | 1       |
|  4 | UserD    | Hello World | null    |
|  5 | UserE    | Hi UserB    | 2       |
+----+----------+-------------+---------+

如何使用分页和displayPerPage = 2显示评论,例如:

UserA: Hello

       UserC: Hi UserA

UserB: Hello

       UserE: Hi UserB

>>More Comments<<

任何帮助将不胜感激。

解决方案1:使用外部加入

1 个答案:

答案 0 :(得分:1)

您可以使用类似于以下内容的查询以正确的顺序获取评论:

select case when c.ReplyId is not null then '        ' else '' end
     + UserName + ': ' + c.content Line
  from Comment c
 order by IsNull(c.ReplyId, c.CommentId), c.commentId