Mysql/Laravel : Using left join to fetch latest created at date of any employee

标签 mysql laravel

Database Structure

我正在尝试使用左连接获取所有部分及其最新的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_id3的记录,但我想要section表的所有记录,如果 section_update_logs 中没有员工记录,则应该有一个 null/空的created_at。

期望的输出是:

  1. 部分的所有行
  2. created_at 日期,如果 sul.section_id = section.idemp_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/

相关文章:

php - 如何在 Lumen 中使用助手实现驱动程序模式

view - 如何在 Laravel 中渲染 View 并将内容保存在文件中

javascript - 生成选择列表项问题

mysql - 使用 whereIn 查询 65k+ 条记录

mysql - 普通字段像 Zerofill 字段一样返回

mysql - SUM() 用于相关表中的多个值

php - PDO - 将字段名称作为变量传递

MySQL - YEAR(FROM_UNIXTIME(col)) 与 EXTRACT(YEAR FROM col)

mysql - 如何将 Angular、Nodejs 和 Mysql Web 应用程序部署到 Heroku?

php - Laravel 使用 groupBy 获取数组数组