首页 > 解决方案 > 在原始帖子之后插入潜在回复时按日期对记录进行排序

问题描述

我意识到标题不清楚,这是我能做到的最好的。我有一个包含用户评论的表格。一条评论可以有一个回复,由 replyTo 字段而不是 0 而是它所引用的评论的 postId 来表示。

CREATE TABLE user_comments (
  postId INT NOT NULL,
  postDate DATETIME NOT NULL,
  replyTo INT NOT NULL DEFAULT (0),
  postText VARCHAR(1000)
)
INSERT INTO user_comments (postId, postDate, replyTo, postText) VALUES(1, '20200930 10:34:09 AM', 0, 'comment 1')
INSERT INTO user_comments (postId, postDate, replyTo, postText) VALUES(2, '20201001 08:20:06 PM', 0, 'comment 2')
INSERT INTO user_comments (postId, postDate, replyTo, postText) VALUES(3, '20201002 09:10:11 AM', 1, 'reply to 1')

我正在尝试按日期(降序)获取所有评论,但如果特定评论有回复(评论 1 有回复),请将其显示在相关评论之后。所以是这样的:

postContext    postId      postDate                  postText
2              2           '20201001 08:20:06 PM'    comment 2
1              1           '20200930 10:34:09 AM'    comment 1
1              3           '20201002 09:10:11 AM'    reply to 1

postContext 将由查询生成并在我的代码中用于“分组”评论及其回复的位置。

我很确定基于 PARTITION BY 的查询可以解决问题,但我找不到正确的方法来实现它。感谢您的任何指示!

标签: sql-servertsql

解决方案


您可以使用自联接,然后ISNULL(或者COALESCE如果您愿意)在几列上获得您想要的值:

SELECT ISNULL(p.postId,uc.postid) AS PostContext,
       uc.postId,
       uc.postDate,
       uc.postText
FROM dbo.user_comments uc
     LEFT JOIN dbo.user_comments p ON uc.replyTo = p.postId
ORDER BY ISNULL(p.postDate,uc.postDate) DESC,
         uc.postDate ASC;

db<>小提琴


推荐阅读