mysql - Laravel Eloquent集团最近的记录




greatest-n-per-group (2)

我正试图在桌面上获得单个客户的最新记录。 例:

ID    Customer    City    Amount
1     Cust001     City1   2
2     Cust001     City2   3
3     Cust001     City1   1
4     Cust001     City2   1
5     Cust001     City2   3
6     Cust001     City3   1
7     Cust001     City3   1
8     Cust002     City1   2
9     Cust002     City1   1
10    Cust002     City2   3
11    Cust002     City1   2
12    Cust002     City2   1
13    Cust002     City3   2
14    Cust002     City3   3
15    Cust003     City1   1
16    Cust003     City2   3
17    Cust003     City3   2

请注意,该表还包含created_at和updated_at字段。 为简单起见我省略了这些字段。

最后,我希望我的查询返回Cust001:

ID    Customer    City    Amount
3     Cust001     City1   1
5     Cust001     City2   3
7     Cust001     City3   1

对于Cust002:

ID    Customer    City    Amount
11    Cust002     City1   2
12    Cust002     City2   1
14    Cust002     City3   3

我试过了:

Table::where('Customer', 'Cust001')
    ->latest()
    ->groupBy('City')
    ->get()

并且

Table::select(DB::raw('t.*'))->from(DB::raw('(select * from table where Customer = \'Cust001\' order by created_at DESC) t'))
    ->groupBy('t.City')->get();

但它不断返回每组最老的记录(我想要最新的记录)。

我怎样才能做到这一点? 如果对你们来说更容易,你可以在这里编写SQL查询,我会找到一种方法将其“翻译”为Laravel语法。


要根据 created_at 获取每个城市中每位客户的最新记录,您可以使用自联接

DB::table('yourTable as t')
  ->select('t.*')
  ->leftJoin('yourTable as t1', function ($join) {
        $join->on('t.Customer','=','t1.Customer')
             ->where('t.City', '=', 't1.City')
             ->whereRaw(DB::raw('t.created_at < t1.created_at'));
   })
  ->whereNull('t1.id')
  ->get();

在简单的SQL中它会是这样的

select t.*
from yourTable t
left join yourTable t1
on t.Customer = t1.Customer
and t.City = t1.City
and t.created_at < t1.created_at
where t1.id is null

Demo

自我内部联接的另一种方法是

select t.*
from yourTable t
join (
    select  Customer,City,max(ID) ID
    from yourTable
    group by Customer,City
) t1
on t.Customer = t1.Customer
and t.City = t1.City
and t.ID = t1.ID

Demo


DB::table('table')->orderBy('id', 'desc')->get();

Laravel查询以获取id的基础上的最新数据





greatest-n-per-group