我正在使用Laravel的查询构建器执行此查询,并使用左连接,并在列s_nid
上链接两个表。在表格中我离开了加入conference_report
的行,其中有一行s_nid
,我只希望找回最近日期的行。我一直在关注Groupwise Maximum,这里有一些关于SO的例子,对我来说是新的,我认为我需要完成查询,但我不确定如何在桌面上实现它我加入
$data['students'] = DB::table('educational_report')
->select('educational_report.s_nid as s_nid'
,'educational_report.name as name'
,'educational_report.file_no as file_no'
,'educational_report.university as university'
,'conference_report.conference_end_date as conference_end_date'
,'student_status.status as status')
->leftJoin('student_status', 'student_status.s_nid', '=', 'educational_report.s_nid')
->leftJoin('conference_report', 'conference_report.s_nid', '=', 'educational_report.s_nid')
->distinct()
->groupBy('s_nid')
->paginate(10);
可能有用的链接:
Performing a Groupwise Maximum in Laravel 4
http://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html
答案 0 :(得分:1)
我认为我没有必要让事情复杂化。我设法使用连接上的嵌套查询来解决这个问题:
$data['students'] = DB::table('educational_report')
->select('educational_report.s_nid as s_nid'
,'educational_report.name as name'
,'educational_report.file_no as file_no'
,'educational_report.university as university'
,'cr2.conference_end_date as conference_end_date'
,'student_status.status as status')
->leftJoin('student_status', 'student_status.s_nid', '=', 'educational_report.s_nid')
->leftJoin(DB::raw('(select s_nid, MAX(conference_end_date) conference_end_date
from conference_report GROUP BY s_nid) as cr2'), function ($join) {
$join->on ( 'cr2.s_nid', '=', 'educational_report.s_nid' );
})
->paginate(10);
它似乎工作正常,但我热衷于任何可能纠正我正在做的事情或提供更好方法的答案。谢谢:))