SQL - 分页注释

问题描述 投票:0回答:1

我有以下表格评论:

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:使用外连接

sql sql-server sql-server-2008 pagination comments
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.