如何根据时间戳获取最新记录但不从 laravel 中的 table 复制?
how to get latest records basis on timestamp but not duplicate from a table in laravel?
我有一个table
引用
id lead_id subject created_at
1 2 Quotation 1 2019-09-03 17:07:17
2 2 Quotation 2 2019-09-04 17:10:30
3 2 Quotation 3 2019-09-05 17:20:57
4 4 Quotation 4 2019-09-06 20:00:21
5 4 Quotation 5 2019-09-07 20:57:17
我需要这样的结果:
id lead_id subject created_at
3 2 Quotation 3 2019-09-05 17:20:57
4 4 Quotation 5 2019-09-07 20:57:17
表示最新的记录,lead_id不重复。
到目前为止,我可以通过此查询获得 lead_id 和 created_at 列,但我想获得完整的行。:
$quotations = DB::table('quotations')
->select('lead_id', DB::raw('MAX(created_at) as created_at'))
->groupBy('lead_id')
->get();
类似
$quotations = DB::table('quotations')
->distinct('lead_id')
->latest()
->get();
您可以使用子查询概念。将上述查询附加为尾查询,并使用 where 语句将另一个主查询添加到 select。
$quotations = DB::table('quotations')
->select('lead_id', DB::raw('MAX(created_at) as created_at'))
->groupBy('lead_id')
->get();
$q = DB:table ('quotations')
->where ('lead_id' , $quotations->lead_id)
->where ('created_at' , $quotations->created_at);
首先按降序对 table 进行排序,然后从集合中选择 unique 行。
$quotations = DB::table('quotations')
->orderBy('created_at','DESC')
->get()
->unique('lead_id');
我有一个table
引用
id lead_id subject created_at
1 2 Quotation 1 2019-09-03 17:07:17
2 2 Quotation 2 2019-09-04 17:10:30
3 2 Quotation 3 2019-09-05 17:20:57
4 4 Quotation 4 2019-09-06 20:00:21
5 4 Quotation 5 2019-09-07 20:57:17
我需要这样的结果:
id lead_id subject created_at
3 2 Quotation 3 2019-09-05 17:20:57
4 4 Quotation 5 2019-09-07 20:57:17
表示最新的记录,lead_id不重复。 到目前为止,我可以通过此查询获得 lead_id 和 created_at 列,但我想获得完整的行。:
$quotations = DB::table('quotations')
->select('lead_id', DB::raw('MAX(created_at) as created_at'))
->groupBy('lead_id')
->get();
类似
$quotations = DB::table('quotations')
->distinct('lead_id')
->latest()
->get();
您可以使用子查询概念。将上述查询附加为尾查询,并使用 where 语句将另一个主查询添加到 select。
$quotations = DB::table('quotations')
->select('lead_id', DB::raw('MAX(created_at) as created_at'))
->groupBy('lead_id')
->get();
$q = DB:table ('quotations')
->where ('lead_id' , $quotations->lead_id)
->where ('created_at' , $quotations->created_at);
首先按降序对 table 进行排序,然后从集合中选择 unique 行。
$quotations = DB::table('quotations')
->orderBy('created_at','DESC')
->get()
->unique('lead_id');