如何在laravel中获取每个用户ID的最新行?

问题描述 投票:0回答:3
id  user_id  name    qty     datetime
--- ---------  ----    ----    -----------
1   1           a      5       2019-12-01 12:26:01
2   2           b      3       2019-12-13 12:26:02
3   1           c      4       2019-12-13 12:26:03
4   2           a      2       2019-12-25 12:26:04
5   1           c      2       2019-12-21 12:26:06

我要这个数据

id  user_id  name    qty     datetime
--- ---------  ----    ----    -----------
5   1           c      2       2019-12-21 12:26:06
4   2           a      2       2019-12-25 12:26:04

使用laravel,如果可能的话,还将使用什么SQL查询

php mysql sql laravel-5 greatest-n-per-group
3个回答
1
投票

在纯SQL中,您可以使用相关的子查询进行过滤:

select t.*
from mytable t
where t.datetime = (
    select max(t1.datetime) from mytable t1 where t1.user_id = t.user_id
)

1
投票

或不相关的子查询...

select x.*
from mytable x
join (
    select user_id, max(t1.datetime) datetime from mytable group by user_id
) y
on y.user_id = x.user_id
and y.datetime = x.datetime

0
投票

型号:

用户: ID,名称,电子邮件等...[订单: user_id,数量,名称,日期时间等。

模型查询:

Orders::orderBy('datetime', 'desc')->get()->unique('user_id');

数据库查询

DB::table('orders')->orderBy('datetime', 'desc')->get()->unique('user_id');
© www.soinside.com 2019 - 2024. All rights reserved.