Laravel 中的 SELECT FROM AS 和 JOIN

Z M*_*ick 2 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
Run Code Online (Sandbox Code Playgroud)

我已经读过 Laravel Documentary 但没有找到任何内容,

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

请帮忙解决这个问题,谢谢。

zga*_*evi 5

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

$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();
Run Code Online (Sandbox Code Playgroud)

如果你想检查这个查询,你可以使用->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`
Run Code Online (Sandbox Code Playgroud)