我正在尝试使用groupby获取最后一行,我有一些重复的jobseeker_id但是不同的call_reason,status,type_of_call等..和created_at。
id jobseeker_id type_of_call status call_reason created_at
1 2001 incoming_call good because of track 2017.10.1
2 2001 outgoing call fair they called me 2017.11.2
3 2001 outgoing call bad something 2017.12.3
4 2002 outgoing call good something 2018.11.6
所以我期望只出来
id jobseeker_id type_of_call status call_reason created_at
1 2001 outgoing call bad something 2017.12.3
4 2002 outgoing call good something 2018.11.6
$jobseekers =DB::table('calllogs')
->select(DB::raw("max(created_at),jobseeker_id,call_reason,type_of_call"))
->orderBy('created_at','desc')
->groupBy('jobseeker_id')
->wherenotnull('call_back_date')
->get();
上面的查询给我回复
id jobseeker_id type_of_call status call_reason created_at
3 2001 incoming_call good because of track 2017.12.3
4 2002 outgoing call good something 2018.11.6
我只能获得最新的created_at日期,但我不会得到最新的staus,type_of_call,call_reason。任何人都有想法?请帮帮我。
不熟悉laravel但你的问题是你需要识别带有id的行,然后从中选择列。您正在尝试获取max created_at,然后只获取其余列的分组值。查询看起来像..
SELECT * FROM calllogs WHERE id IN (
(SELECT MAX(ID) FROM calllogs GROUP BY jobseeker_id);
我假设您显示的预期结果中的id应该是3而不是1.查询应该至少对我能看到的有限集合起作用。可能需要根据其余数据添加更多优化,但这可以让您了解可能有用的内容。希望这可以帮助。
$jobseekers =DB::table('calllogs')
->select(DB::raw("max(created_at),jobseeker_id,call_reason,type_of_call"))
->orderBy('jobseeker_id','desc')
->wherenotnull('call_back_date')
->take(2)
->get();