1

我正在使用 Laravel 的查询构建器执行此查询,该查询构建器具有左连接,两个表在 column 上链接s_nid。有了我要加入的表格,conference_report有很多行只有一个s_nid,我只想取回最近日期的行。我一直在查看 Groupwise 最大值,这里有一些关于 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);

可能有用的链接:

在 Laravel 4 中执行分组最大值

分组最大值

http://dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html

4

1 回答 1

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);

它似乎工作正常,但我热衷于任何可能纠正我正在做的事情或提供更好的方法的答案。谢谢 :)

于 2014-09-05T11:39:35.617 回答