Laravel orderby with groupby sql

时间:2016-12-12 04:27:28

标签: mysql laravel eloquent

您好我正在尝试使用orderby和groupby一起查询,并提出了这个解决方案,这是正常工作是我的查询

SELECT p1.year_id,p1.tbl_wsp_master_id ,tbl_wsp_masters.WSP_Name
FROM tbl_wsp_years p1
INNER JOIN
(
    SELECT max(year_id) MaxPostDate,tbl_wsp_master_id
    FROM tbl_wsp_years
    GROUP BY tbl_wsp_master_id
) p2
  ON p1.tbl_wsp_master_id = p2.tbl_wsp_master_id
  AND p1.year_id = p2.MaxPostDate
INNER JOIN tbl_wsp_masters
 ON tbl_wsp_masters.id = p1.tbl_wsp_master_id    
order by p1.year_id desc

但我如何在Laravel Eloquent中这样做 感谢您的任何建议

1 个答案:

答案 0 :(得分:0)

我这样解决了,谢谢

DB::table('tbl_wsp_years as y1')
        ->join('tbl_wsp_masters', 'tbl_wsp_masters.id', '=', 'y1.tbl_wsp_master_id')
        ->select('tbl_wsp_masters.WSP_Name AS WSP_Name', 'y2.*')
        ->join(DB::raw('(SELECT MAX(year_id) MaxYear, tbl_wsp_master_id FROM tbl_wsp_years GROUP BY tbl_wsp_master_id) y2'), 
                function($join)
                {
                    $join->on('y1.tbl_wsp_master_id', '=', 'y2.tbl_wsp_master_id');
                    $join->on('y1.year_id','=','y2.MaxYear');
                })
        ->orderBy('y1.year_id', 'DESC')
        ->get();