これが私のテーブルです
+------------+-----------+---------------+--------------+
| 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