这是我的桌子
+------------+-----------+---------------+--------------+
| 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