我正在尝试使用左连接获取所有部分及其最新的created_at
我正在使用以下查询
select es.*, sul.created_at as created_at from section as es
left join section_update_logs as sul on es.id = sul.section_id
where sul.emp_id = 3
group by es.id
order by es.id, sul.created_at asc;
查询的明显输出仅显示emp_id
为3
的记录,但我想要section
表的所有记录,如果 section_update_logs
中没有员工记录,则应该有一个 null/空的created_at。
期望的输出是:
- 表
部分
的所有行 created_at
日期,如果sul.section_id
=section.id
且emp_id
= 特定员工。<
Laravel 查询:
$result = DB::table("section as es")
->select('es.*', 'sul.created_at')
->leftJoin('section_update_logs as sul', 'es.id', '=', 'sul.section_id')
->orderBy('es.weight')
->orderBy('sul.created_at')
->orWhere('sul.emp_id', $emp_id)
->groupBy('es.id')
->get();
请帮忙
最佳答案
您可以向 leftJoin
添加一个闭包功能添加更多条件。
$result = DB::table("section as es")
->select('es.*', DB::raw('MAX(sul.created_at)'))
->leftJoin('section_update_logs as sul', function ($join) use ($emp_id) {
$join->on('es.id', '=', 'sul.section_id')
->where('sul.emp_id', $emp_id);
})
->orderBy('es.weight')
->orderBy('sul.created_at')
->groupBy('es.id')
->get();
这样,sul.emp_id
上的过滤器仅在找到关系时才会验证。
要通过 SQL 查询获得相同的结果,请使用 AND
在联接中添加第二个条件:
select es.*, MAX(sul.created_at) as created_at from section as es
left join section_update_logs as sul on es.id = sul.section_id AND sul.emp_id = 3 -- HERE
group by es.id
order by es.id, sul.created_at asc;
关于Mysql/Laravel : Using left join to fetch latest created at date of any employee,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56580120/