MySQL排序DESC和ASC

时间:2017-08-28 22:34:49

标签: mysql sql sorting

我有一个包含字段的表:

id | group_id
1  | null
2  | null
3  | null
4  | 4
5  | 4
6  | 4
7  | 7
8  | 7
9  | null

我希望将其排序为:

id | group_id
9  | null
7  | 7
8  | 7
4  | 4
5  | 4
6  | 4
3  | null
2  | null
1  | null

所以它的整体ID是DESC,但是当他们共享group_id时是id的ASC

谢谢

3 个答案:

答案 0 :(得分:2)

试一试

Select id, group_id, coalesce(group_id, id) from table order by 3 desc, 1

答案 1 :(得分:2)

我让这个工作:

SELECT id, group_id, rank
FROM (
  SELECT id, group_id, 
    @rank:=IF(group_id=@group_id,@rank,@rank+1) AS rank,
    @group_id:=group_id
  FROM MyTable CROSS JOIN (SELECT @rank:=0) AS _init
  ORDER BY id DESC
) AS t
ORDER BY rank ASC, id ASC;

输出:

+----+----------+------+
| id | group_id | rank |
+----+----------+------+
|  9 |     NULL | 1    |
|  7 |        7 | 2    |
|  8 |        7 | 2    |
|  4 |        4 | 3    |
|  5 |        4 | 3    |
|  6 |        4 | 3    |
|  3 |     NULL | 4    |
|  2 |     NULL | 5    |
|  1 |     NULL | 6    |
+----+----------+------+

您可以省略外部查询的选择列表中的rank列,我将其留在那里只是为了说明我如何对这些组进行排名。

答案 2 :(得分:0)

我不确定你可以对id列进行无序排序,但是如果你需要的是共享组id的最低id,那么像这样更新@ Lamar的答案就可以了/ p>

SELECT MIN(id) AS id, group_id FROM table
GROUP BY group_id
ORDER BY IFNULL(group_id, 0) DESC, id DESC