我有一个mysql表,用于存储带有架构的注释和子注释:
id
,replyTo
,text
其中replyTo
可能为空,如果评论不是子评论。
目前我正在进行以下查询:
(select id as replyTo, text from Comments WHERE replyTo IS NULL)
UNION
(select replyTo,text from Comments WHERE replyTo IS NOT NULL) ORDER BY replyTo;
这给了我订单中的评论:
1. comment
2. subcomment
所以,如果我有:
+----+---------+-----------+
| id | replyTo | text |
+----+---------+-----------+
| 1 | NULL | comment 1 |
| 2 | NULL | comment 2 |
| 3 | 1 | sub 1 |
| 4 | 2 | sub 2 |
+----+---------+-----------+
这给出了:
+---------+-----------+
| replyTo | text |
+---------+-----------+
| 1 | comment 1 |
| 1 | sub 1 |
| 2 | comment 2 |
| 2 | sub 2 |
+---------+-----------+
我的问题是,我如何以相反的顺序得到它们,就像这样:
+-+------------+
|2|comment 2 |
|2|sub 2 |
|1|comment 1 |
|1|sub 1 |
+-+------------+
换句话说,我想按replyTo ASC
对元素进行排序,将它们按replyTo
分组(而不是在mysql GROUP BY中,它会根据属性删除所有重复的行),然后按replyTo DESC
排序。
答案 0 :(得分:2)
尝试
SELECT COALESCE(replyTo,id) AS replyTo, text
FROM Comments
ORDER BY COALESCE(replyTo,id) DESC, id
答案 1 :(得分:0)
试试这个:
select replyTo, text from
(
select id as replyTo, text from Comments WHERE replyTo IS NULL
UNION
select replyTo,text from Comments WHERE replyTo IS NOT NULL ORDER BY replyTo
)
order by replyTo DESC;