duanguane1670 2015-07-06 12:38
浏览 60
已采纳

如何按一列排序,然后将同一列id的最新块推到顶部?

For example I have table:

|    id    |    title    |    created_at    |

     1                            12:00           
     2                            13:00
     2                            14:00
     1                            15:00

I want same id numbers to be near each other. In this case 1 1 2 2 or 2 2 1 1 AND order same chunks of id's by created_at time so the chunk of id's which own the latest created_at stays on top, then goes one, having highest created_at compared to 3rd chunk of id's and so on. How do I do it?

orderBy('id', 'desc')->orderBy('created_at', 'desc')->get(); // orders id's to same id chunks, but it doesn't sort that the chunk with latest id chunk (1 1) created_at at the top.

orderBy('created_at', 'desc')->orderBy('id', 'desc')->get(); // gives the latest created_at at top and so on, but same id's arent close to each other.

Bigger example:

|    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

Want to anchieve that foreach($table_rows as $row) { } would give me result:

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

I know it's hard to do with mysql alone. How do I do this in php easiest way?

I bet I have to sort by id first and then push each id's chunk relative to each other by latest created_at.

  • 写回答

1条回答 默认 最新

  • dstd2129 2015-07-06 12:53
    关注

    You need to get the information of the most recent date for each id. Here is a method using join and an aggregation:

    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;
    

    The rest is just the order by using the maximum value.

    I don't know how to express this in laravel, but your question is also tagged mysql.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?