gpt4 book ai didi

php - 按电子邮件分组并获取组中最早创建的日期 - Laravel Eloquent

转载 作者:行者123 更新时间:2023-11-29 09:58:30 25 4
gpt4 key购买 nike

在 Eloquent 语句中使用 groupBy 时,如何获得最早的created_at日期?

我有一个包含以下内容的表格:

| id | name   | email   | created_at          |
|----|--------|---------|---------------------|
| 1 | test | 1@1.com | 2018-01-01 09:00:00 |
| 2 | test | 1@1.com | 2018-01-02 09:00:00 |
| 3 | test 2 | 2@2.com | 2018-01-02 09:00:00 |
| 4 | test 2 | 2@2.com | 2018-01-03 09:00:00 |
| 5 | test | 1@1.com | 2018-01-03 09:00:00 |
| 6 | test | 1@1.com | 2018-01-04 09:00:00 |
| 7 | test | 1@1.com | 2018-01-05 09:00:00 |
| 8 | test 3 | 3@3.com | 2018-01-06 09:00:00 |
| 9 | test 3 | 3@3.com | 2018-01-07 09:00:00 |

运行以下查询时:

Customers::OrderBy('created_at', 'desc')->groupBy('email')->paginate('5');

我期望按以下顺序获得结果:

Test 3 (created: 2018-01-07)
Test (created: 2018-01-05)
Test 2 (created: 2018-01-03)

但相反,我发现它看起来并不尊重 OrderBy

Test 3 (created: 2018-01-06)
Test 2 (created: 2018-01-02)
Test (created: 2018-01-01)

这是 SQL fiddle http://sqlfiddle.com/#!9/89ee39/2

# 编辑 - 根据响应回答

感谢 Nesku,最终使该工作正常运行的查询是:

 return DB::table('customers')
->select(DB::raw('email, max(created_at)'))
->groupBy('email')
->orderBy('max(created_at)', 'desc')
->get();

最佳答案

您无法按 created_at 进行排序,因为它包含多个值,但是您可以为每封电子邮件取 created_at 的最大值并按该值进行排序。

SQL 查询如下所示:

SELECT email, max(created_at)
FROM `customers`
GROUP BY email
ORDER BY max(created_at) DESC

http://sqlfiddle.com/#!9/89ee39/12

关于php - 按电子邮件分组并获取组中最早创建的日期 - Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53450987/

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