SQL - 分页评论
SQL - Paging comments
我在下面有 Table 评论:
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: 使用 Outer Join
您可以使用类似于以下的查询来按正确的顺序获取评论:
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
我在下面有 Table 评论:
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: 使用 Outer Join
您可以使用类似于以下的查询来按正确的顺序获取评论:
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