Mysql
 sql >> Database >  >> RDS >> Mysql

Gruppo Laravel Eloquent per record più recente

Per ottenere l'ultimo record per cliente per ogni città in base a created_at puoi usare un self join

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();

In semplice SQL sarebbe qualcosa come

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

Un altro approccio con il self inner join sarebbe

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