如何 select 按日期列 desc 排序的不同记录 - Laravel
How to select distinct records ordered by date column desc - Laravel
我有这样的 table:
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
我尝试了不同的方法,但我不明白为什么它没有像我预期的那样工作。
你能帮忙吗?
您可以通过两种方式实现此行为。第一个是在查询中过滤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');
我有这样的 table:
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
我尝试了不同的方法,但我不明白为什么它没有像我预期的那样工作。 你能帮忙吗?
您可以通过两种方式实现此行为。第一个是在查询中过滤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');