我有一个这样的表,它显示哪个用户评论了哪个父线程。
ParentID CommentID UserName CommentDateTime
58 58 Vicky 2016-12-02 11:51:07.270
58 61 Billu 2016-12-02 12:35:40.220
58 62 Rakesh 2016-12-02 12:37:42.133
如果假设对第2行发表评论,则会生成新的荣誉,即63
我想编写一个sql查询,按以下顺序列出行:
ParentID CommentID UserName CommentDateTime
58 58 Vicky 2016-12-02 11:51:07.270
58 61 Billu 2016-12-02 12:35:40.220
61 63 Rakesh 2016-12-02 13:37:42.133
58 62 Rakesh 2016-12-02 12:37:42.133
请你帮我写一个逻辑/ SQL吗?
答案 0 :(得分:1)
如果我说得对,你想按所需顺序输出记录,不要将它们插入表中。在这里,我们看到了一个帖子的TREE,所以我认为你应该使用recursive CTE。对于每个节点,我们构建一个PATH字符串,然后使用此路径字符串对节点进行排序:
WITH CTE AS
(
SELECT ParentID, CommentID, UserName, CommentDateTime,
ParentID as ThreadID,
CAST(ParentID as varchar(MAX)) as PathStr
FROM T
WHERE CommentID = T.ParentID
UNION ALL
SELECT T.ParentID, T.CommentID, T.UserName, T.CommentDateTime,
CTE.ThreadID,
PathStr+'-'
+CAST(T.CommentID as varchar(MAX)) as PathStr
FROM T
JOIN CTE ON CTE.CommentID = T.ParentID
WHERE T.CommentID <> T.ParentID
)
SELECT * FROM CTE ORDER BY ThreadID,PathStr
我已经在示例表中添加了更多节点,因此结果如下:
╔══════════╦═══════════╦══════════╦═════════════════════════╦══════════╦═════════════╗
║ ParentID ║ CommentID ║ UserName ║ CommentDateTime ║ ThreadID ║ PathStr ║
╠══════════╬═══════════╬══════════╬═════════════════════════╬══════════╬═════════════╣
║ 58 ║ 58 ║ Vicky ║ 2016-12-02 11:51:07.270 ║ 58 ║ 58 ║
║ 58 ║ 61 ║ Billu ║ 2016-12-02 12:35:40.220 ║ 58 ║ 58-61 ║
║ 61 ║ 63 ║ Rakesh ║ 2016-12-02 13:37:42.133 ║ 58 ║ 58-61-63 ║
║ 58 ║ 62 ║ Rakesh ║ 2016-12-02 12:37:42.133 ║ 58 ║ 58-62 ║
║ 158 ║ 158 ║ Vicky ║ 2016-12-02 11:51:07.270 ║ 158 ║ 158 ║
║ 158 ║ 161 ║ Billu ║ 2016-12-02 12:35:40.220 ║ 158 ║ 158-161 ║
║ 161 ║ 163 ║ Rakesh ║ 2016-12-02 13:37:42.133 ║ 158 ║ 158-161-163 ║
║ 161 ║ 164 ║ Rakesh ║ 2016-12-02 13:37:42.133 ║ 158 ║ 158-161-164 ║
║ 158 ║ 162 ║ Rakesh ║ 2016-12-02 12:37:42.133 ║ 158 ║ 158-162 ║
╚══════════╩═══════════╩══════════╩═════════════════════════╩══════════╩═════════════╝