0

这是我的桌子

+------------+-----------+---------------+--------------+
| CommentId  | ParentId  |  Timestamp    | CommentText  |
+------------+---------+-----------+--------------------+
|          1 |      NULL |  Jan 1 2:00pm |          a   |
|          2 |      NULL |  Jan 1 2:01pm |          b   |
|          3 |         1 |  Jan 1 3:03pm |          c   |
|          4 |         2 |  Jan 1 5:00pm |          d   |
|          5 |         2 |  Jan 1 5:01pm |          e   |
|          6 |      NULL |  Jan 1 8:00pm |          f   |
|          7 |         1 |  Jan 1 7:00pm |          g   |
|          8 |         6 |  Jan 1 9:04pm |          h   |
|          9 |         1 |  Jan 1 8:05pm |          i   |
|         10 |      NULL |  Jan 1 9:04pm |          k   |
+------------+-----------+---------------+--------------+

目前我正在使用以下 SQL 来返回父级排序的评论

SELECT c.*
FROM Comments c
ORDER BY COALESCE(c.ParentId, c.Id)

结果是这样的:

+------------+-----------+---------------+--------------+
| CommentId  | ParentId  |  Timestamp    | CommentText  |
+------------+---------+-----------+--------------------+
|          1 |      NULL |  Jan 1 2:00pm |          a   |
|          3 |         1 |  Jan 1 3:03pm |          c   |
|          7 |         1 |  Jan 1 7:00pm |          g   |
|          9 |         1 |  Jan 1 8:05pm |          i   |    
|          2 |      NULL |  Jan 1 2:01pm |          b   |    
|          4 |         2 |  Jan 1 5:00pm |          d   |
|          5 |         2 |  Jan 1 5:01pm |          e   |
|          6 |      NULL |  Jan 1 8:00pm |          f   |    
|          8 |         6 |  Jan 1 9:04pm |          h   |    
|         10 |      NULL |  Jan 1 9:04pm |          k   |
+------------+-----------+---------------+--------------+

我需要以降序时间戳顺序获取结果。结果集应如下所示:

 +------------+-----------+---------------+--------------+
| CommentId  | ParentId  |  Timestamp    | CommentText  |
+------------+---------+-----------+--------------------+         
|         10 |      NULL |  Jan 1 9:04pm |          k   |
|          6 |      NULL |  Jan 1 8:00pm |          f   |    
|          8 |         6 |  Jan 1 9:04pm |          h   |    
|          2 |      NULL |  Jan 1 2:01pm |          b   |    
|          5 |         2 |  Jan 1 5:01pm |          e   |
|          4 |         2 |  Jan 1 5:00pm |          d   |
|          1 |      NULL |  Jan 1 2:00pm |          a   |
|          9 |         1 |  Jan 1 8:05pm |          i   |
|          7 |         1 |  Jan 1 7:00pm |          g   |
|          3 |         1 |  Jan 1 3:03pm |          c   |    
+------------+-----------+---------------+--------------+

以下不起作用:

SELECT c.*
FROM Comments c
ORDER BY COALESCE(c.ParentId, c.Id), Timestamp DESC
4

1 回答 1

1

我认为此查询按您想要的顺序返回行:

SELECT c.*
FROM Comments c
ORDER BY
  COALESCE(ParentID, ID) DESC,
  ParentID is not null,
  Timestamp DESC

如果 ParentID 不为 null,它会按降序对行进行排序,否则按 ID 排序,然后有 null 的行排在最前面,然后按时间戳降序排列。

于 2012-11-09T20:02:40.223 回答