gpt4 book ai didi

php - 在 Laravel 中从 AS 中选择并加入

转载 作者:行者123 更新时间:2023-11-29 04:16:37 25 4
gpt4 key购买 nike

如何在 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 中执行此查询。

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

最佳答案

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

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

关于php - 在 Laravel 中从 AS 中选择并加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42056724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com