在Laravel中选择从AS和JOIN

时间:2017-02-05 20:09:24

标签: php mysql laravel

如何在Laravel上执行此查询?

SELECT * 
FROM conversion t1 
     JOIN (SELECT report_id, MAX(id) id 
           FROM conversion 
           GROUP BY report_id ) AS t2 
     ON t1.id = t2.id AND t1.report_id = t2.report_id

我已经读过Laravel纪录片而没有找到任何东西,

我已经尝试过SQL并且正在工作,但我不知道如何在Laravel中执行此查询。

请帮助解决此问题,谢谢。

2 个答案:

答案 0 :(得分:4)

我认为这是您问题的正确解决方案:

$subQuery = \DB::table('conversion')
    ->selectRaw('report_id, MAX(id) id')
    ->groupBy('report_id')
    ->toSql();

$data = \DB::table('conversion t1')
    ->join(\DB::raw('(' . $subQuery . ') as t2'), function ($join) {
        $join->on('t1.id', 't2.id')
            ->on('t1.report_id', 't2.report_id');
    }, null, null, '')
    ->get();

如果您想查看此查询,最后可以使用->toSql()代替->get()。 输出是:

select * 
from `conversion t1` 
join (
    select report_id, MAX(id) as id 
    from `conversion` 
    group by `report_id`
) as t2 
on `t1`.`id` = `t2`.`id` 
and `t1`.`report_id` = `t2`.`report_id`

答案 1 :(得分:1)

现在没有我的IDE,但它应该这样工作:

$results = DB::select(DB::raw ('SELECT * 
    FROM conversion t1 
    JOIN (SELECT report_id, MAX(id) id 
       FROM conversion 
       GROUP BY report_id ) AS t2 
       ON t1.id = t2.id AND t1.report_id = t2.report_id'));