简体   繁体   English

MySQL排序DESC和ASC

[英]MySQL sort DESC and ASC

I have a table with the fields: 我有一个带有字段的表:

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

and I'd like to sort it to be: 我想将其排序为:

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

So for it to be DESC by id overall, but ASC by id when they share a group_id 因此,总体而言,将其按ID排序为DESC,但当他们共享group_id时按ID排序

Thank you 谢谢

试试吧

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

I got this to work: 我得到这个工作:

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;

Output: 输出:

+----+----------+------+
| 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    |
+----+----------+------+

You can omit the rank column from the select-list of the outer query, I left it in there just to illustrate how I ranked the groups. 您可以从外部查询的选择列表中忽略rank列,我将其留在此处只是为了说明如何对组进行排名。

I'm not sure you can do the out-of-sequence ordering of the id column, but if what you need is the lowest id where the group id is shared, then updating @Lamar's answer like this would do it 我不确定您是否可以对id列进行无序排序,但是如果您需要的是共享组ID的最低ID,那么像这样更新@Lamar的答案就可以了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM