【问题标题】:How to select distinct records ordered by date column desc - Laravel如何选择按日期列 desc 排序的不同记录 - Laravel
【发布时间】:2019-10-14 18:36:40
【问题描述】:

我有这样的桌子:

app_id | releaseDate 
111  | 2019-04-21
111  | 2019-05-10
222  | 2019-07-21
222  | 2019-04-22
222  | 2019-05-25
333  | 2019-06-21
333  | 2019-05-21

我需要得到这样的结果(需要在 releaseDate 和 select distinct 之后订购 desc):

111 | 2019-05-10
222 | 2019-07-21
333 | 2019-06-21

我的代码:

$apps_histories = ApplicationHistory::with('application')->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
            ->orderBy('releaseDate', 'DESC')
            ->groupBy('app_id')
            ->get();

我明白了:

111 | 2019-04-21
222 | 2019-04-22
333 | 2019-05-21

我尝试了不同的方法,但我不明白为什么它没有按预期工作。 你能帮忙吗?

【问题讨论】:

  • 如果您使用 group by 任何不在 group by 中的列,应该在聚合运算符中,如 MAX、MIN、SUM、AVG。即 MAX(releaseDate)

标签: mysql sql laravel laravel-5 distinct


【解决方案1】:

您可以通过两种方式实现此行为。第一个是在查询中过滤releaseDate,使用原始查询:

$apps_histories = ApplicationHistory::with('application')
        ->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
        ->select(\DB::raw('*, max(releaseDate) as releaseDate'))
        ->orderBy('releaseDate', 'DESC')
        ->groupBy('app_id')
        ->get();

另一种方法是在结果Collection 中使用unique 函数。请注意,此选项未针对大型结果表进行优化:

$apps_histories = ApplicationHistory::with('application')
        ->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
        ->orderBy('releaseDate', 'DESC')
        ->get()
        ->unique('app_id');

【讨论】:

  • 两种方式都正常工作,谢谢。一个大的结果表(大约)多少钱?
  • 这取决于服务器容量,但是,假设您要过滤 10,000 个对象,也许第二个选项不是一个好主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 2013-01-17
  • 2020-09-24
  • 1970-01-01
  • 2016-06-07
  • 2023-03-22
相关资源
最近更新 更多