gpt4 book ai didi

mysql - Laravel Eloquent 组按最新记录

转载 作者:行者123 更新时间:2023-11-30 21:21:43 24 4
gpt4 key购买 nike

我正在尝试获取一张 table 上单个客户的最新记录。示例:

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

另一种 self 内连接的方法是

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

关于mysql - Laravel Eloquent 组按最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com