4

我将数据存储在我的数据库中。存储的数据如下所示

id  | upload_month | created_at
-----------------------------------------
1   | January      | 2017-01-30 13:22:39
-----------------------------------------
2   | Febuary      | 2017-01-30 13:23:42
-----------------------------------------
3   | January      | 2017-01-30 13:25:33

在我的控制器中,我试图检索不同的 upload_month,但获取每个最新插入的版本。目前我正在尝试

$uploadedFile = UploadedFile::groupBy('upload_month')->orderBy('created_at', 'desc')->get();

问题是这将返回以下内容

id  | upload_month | created_at
-----------------------------------------
1   | January      | 2017-01-30 13:22:39
-----------------------------------------
2   | Febuary      | 2017-01-30 13:23:42
-----------------------------------------

因此,对于一月份的记录,它提供的是旧版本。如果我将其更改为->orderBy('created_at', 'asc')它返回相同的记录,但二月是第一行。

从本质上讲,我追求的是这个

id  | upload_month | created_at
-----------------------------------------
1   | January      | 2017-01-30 13:25:33
-----------------------------------------
2   | Febuary      | 2017-01-30 13:23:42
-----------------------------------------

我怎样才能做到这一点?

谢谢

4

3 回答 3

4

您应该GROUP BY选择所有要选择的字段,而不仅仅是一个。这篇文章解释了这个问题:https ://www.psce.com/blog/2012/05/15/mysql-mistakes-do-you-use-group-by-correctly/

在这种情况下,正确的 SQL 查询将是:

SELECT id, upload_month, created_at
  FROM uplodaded_file
  JOIN (SELECT upload_month, MAX(created_at) created_at
          FROM uplodaded_file
      GROUP BY upload_month) months
    ON upload_month = months.upload_month
   AND created_at = months.created_at

雄辩的版本有点棘手。在这种情况下,最好使用原始查询。

于 2017-01-30T16:13:07.210 回答
1

我遇到了这个问题并以这种方式解决了它。

UploadedFile::select(DB::raw('upload_month, MAX(created_at) as latest_date'))
->groupBy('upload_month')->orderBy('latest_date', 'desc')->get()
于 2021-07-22T07:22:41.410 回答
1

您应该使用 latest() 方法而不是 orderBy:

UploadedFile::latest()->distinct()->get();
于 2017-01-31T09:20:16.873 回答