mysql - Laravel Eloquent集團最近的記錄




greatest-n-per-group (2)

要根據 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

我正試圖在桌面上獲得單個客戶的最新記錄。 例:

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語法。


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

Laravel查詢以獲取id的基礎上的最新數據





greatest-n-per-group