【问题标题】:Distinct most recent data from database从数据库中区分最新数据
【发布时间】:2017-01-30 14:44:28
【问题描述】:

我将数据存储在我的数据库中。存储的数据是这样的

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
-----------------------------------------

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

本质上,我追求的是这个

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

我怎样才能做到这一点?

谢谢

【问题讨论】:

标签: laravel laravel-5 laravel-eloquent


【解决方案1】:

你应该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

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

【讨论】:

    【解决方案2】:

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

    UploadedFile::latest()->distinct()->get();
    

    【讨论】:

    • 不幸的是,它不会返回唯一的月份。我将返回所有 3 个结果。
    • 尝试使用最新的 groupBy('upload_month')。
    • 现在返回两个月,但不是最新的一月
    • 试试这个 UploadedFile::groupBy('upload_month')->latest()->distinct()->get();
    【解决方案3】:

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

    UploadedFile::select(DB::raw('upload_month, MAX(created_at) as latest_date'))
    ->groupBy('upload_month')->orderBy('latest_date', 'desc')->get()
    

    【讨论】:

    • 请对您的回答进行详细解释,以便下一位用户更好地理解您的回答。
    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2012-07-21
    相关资源
    最近更新 更多