例如我有桌子:
| id | title | created_at |
1 12:00
2 13:00
2 14:00
1 15:00
我希望相同的ID号彼此靠近。在这种情况下1 1 2 2或2 2 1 1并且通过created_at时间对id的相同块进行排序,因此拥有最新created_at的id的块保持在顶部,然后变为one,具有最高的created_at与第三块id相比,等等。我该怎么做?
orderBy('id', 'desc')->orderBy('created_at', 'desc')->get();
//将id命令发送到相同的id块,但它并不排序顶部有最新id块(1 1)created_at的块。
orderBy('created_at', 'desc')->orderBy('id', 'desc')->get();
//在最顶层提供最新的created_at,依此类推,但相同的ID并不相互接近。
更大的例子:
| 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
想要获得那个foreach($ table_rows as $ row){}会给我结果:
3 20:00
3 18:00
1 19:00
1 17:00
1 15:00
1 12:00
2 15:00
2 13:00
我知道单独使用mysql很难。我怎么用php最简单的方式做到这一点?
我打赌我必须首先按id排序,然后通过最新的created_at将每个id的块相对于彼此推送。
答案 0 :(得分:0)
您需要获取每个ID的最新日期信息。以下是使用join
和聚合的方法:
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;
其余的只是使用最大值的order by
。
我不知道如何在laravel中表达这个,但你的问题也标记为mysql。