对每个组进行分组排序

时间:2016-06-14 00:36:41

标签: mysql sorting group-by

我有一个mysql表,用于存储带有架构的注释和子注释: idreplyTotext其中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排序。

2 个答案:

答案 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;