Php 从AS中选择并加入Laravel

Php 从AS中选择并加入Laravel,php,mysql,laravel,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 我已经在拉威尔的纪录片里看过了,但什么也没找到 我已经在SQL中尝试并正在工作,

如何在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
我已经在拉威尔的纪录片里看过了,但什么也没找到

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


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

现在没有我的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'));

我现在没有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'));

我认为这是你问题的正确答案:

$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`

我认为这是你问题的正确答案:

$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`