如何按列对组内元素进行排序?

时间:2015-07-06 14:23:56

标签: php mysql

尝试订购:

|    id    |    title    |    created_at    |

 1                            12:00  
 2                            13:00
 1                            15:00
 2                            15:00
 1                            17:00
 3                            18:00
 1                            19:00
 3                            20:00

进入这个:

3    20:00
3    18:00
1    19:00
1    17:00
1    15:00
1    12:00
2    15:00
2    13:00

这种代码的和平完成了工作分组ID:

select t.*
from table t join
     (select t.id, max(created_at) as maxca
      from table t
      group by t.id
     ) tt
     on t.id = tt.id
order by tt.maxca desc, id;

问题是created_at以相反的顺序出现,如下所示:

3    18:00
3    20:00
1    12:00
1    15:00
1    18:00
1    19:00
2    13:00
2    15:00

如何在每个分组的id块中反转created_at顺序?

3 个答案:

答案 0 :(得分:0)

select * from table order by id desc,created_at desc

答案 1 :(得分:0)

只需向order by添加另一个密钥:

select t.*
from table t join
     (select t.id, max(created_at) as maxca
      from table t
      group by t.id
     ) tt
     on t.id = tt.id
order by tt.maxca desc, id, created_at desc;

答案 2 :(得分:0)

所以你必须删除 tt.maxca 并在你的分组中添加 created_at

select t.*
from table t join
     (select t.id, max(created_at) as maxca
      from table t
      group by t.id
     ) tt
     on t.id = tt.id
order by id desc, created_at desc;