我有两个类似的表条目,如下所示:gym_clients+---------+---------+-----------------+| id | first_name| last_name |+---------+-----------+---------------+| 1 | Name 1 | Last 1 || 2 | Name 2 | Last 2 |+---------+-----------+---------------+gym_client_purchases+---------+---------+-----------------+| id | client_id | purchase_date |+---------+-----------+---------------+| 15 | 1 | 2018-04-01 || 16 | 1 | 2018-05-01 || 17 | 2 | 2018-05-01 |+---------+-----------+---------------+我想按每个客户的购买分组并显示最新的。我试过这个查询,但 groupby 显示了我最旧的购买(ID 15)。有任何想法吗? $this->data['latestSubscriptions'] = GymPurchase::select('first_name', 'last_name', 'gym_client_purchases.*') ->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id') ->groupBy('gym_client_purchases.client_id') ->orderBy('gym_client_purchases.purchase_date', 'desc') ->get(); 提前致谢。
2 回答
鸿蒙传说
TA贡献1865条经验 获得超7个赞
首先,当您使用 group by 时,您必须在此子句中指定查询要对其进行分组的列,因此我建议您尝试在 sql 引擎上查询。
你会有这样的事情
select first_name, last_name, A.*
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By A.purchase_date desc
你会注意到它不起作用
也许你想要的是这样的
select A.client_id, B.first_name, B.last_name, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id, B.first_name, B.last_name
order By max(A.purchase_date) desc
- 2 回答
- 0 关注
- 448 浏览
添加回答
举报
0/150
提交
取消