sql-server - 在原始帖子之后插入潜在回复时按日期对记录进行排序
问题描述
我意识到标题不清楚,这是我能做到的最好的。我有一个包含用户评论的表格。一条评论可以有一个回复,由 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 的查询可以解决问题,但我找不到正确的方法来实现它。感谢您的任何指示!
解决方案
您可以使用自联接,然后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;
推荐阅读
- azure-active-directory - 模拟 Azure AD 用户
- python - 在 Python 中比较相同的图像
- c - 计算 C 关键字中的出现次数:getch() 未返回正确值的问题
- python - 如何在数据帧上执行分组和求和。我有一个 Dataframe1 我想像这样转换成 Dataframe2
- java - 为什么它说类 dog 中的构造函数 dog 不能应用于给定类型?它似乎运行但抛出错误,这是为什么呢?
- python - 程序成功执行,退出代码为 0,但没有打印任何内容
- grafana - zabbix 图表仅适用于 6 小时的时间范围?
- java - 如何在 JavaFX 中从另一个场景编辑一个场景中的标签
- python - 具有多个输出和自定义损失函数的模型
- python - 如何使用 Tkinter 应用程序只保存填写的条目小部件而不将空的条目小部件保存在文本文件中?