首页 > 解决方案 > 如何左连接然后使用 where date 获取第二个表中的最新行

问题描述

有谁知道如何查询这个示例表?

imgur 上的图片

我认为这是从表branchesbranch_operationals我应该放在where date查询中的表的左连接。

以下是示例:

桌子branches

ID 代码 姓名
1 T2QD5 NewYork_Spot
2 MKGHB London_Spot
3 IGHCZ Miami_Spot
4 PJDSO Tokyo_Spot

桌子branch_operationals

ID branch_id 日期 地位
1 2 2020-12-05 关闭
2 2 2020-12-06 关闭
3 3 2020-12-06 打开
4 2 2020-12-06 关闭
5 2 2020-12-06 打开
6 1 2020-12-16 关闭

预期结果

id(来自'branches.id') 代码 姓名 日期 地位
1 T2QD5 NewYork_Spot 2020-12-09 关闭
2 MKGHB London_Spot 2020-12-09 打开
3 IGHCZ Miami_Spot 2020-12-09 打开
4 PJDSO Tokyo_Spot 2020-12-09 无效的

这是我当前的查询:

select * from `branches` left join `branch_operationals` on `branches`.`id` = `branch_operationals`.`branch_id` where (`date` = 2020-12-21)

但是,它返回 null(空数据)。但是当我删除该where语句时,它会显示 table 中的所有数据以及 tablebranch_operationals中的每个数据branches

目前我正在使用 Laravel 8,这是我的 Laravel 语法:

$branches = Branch::leftJoin('branch_operationals','branches.id','branch_operationals.branch_id')->where(function($q) use($request){
    if($request->search){
        $q->where(function($q) use($request){
            $q->where('code','like','%'.$request->search.'%');
            $q->orWhere('name','like','%'.$request->search.'%');
        });
    }

    if($request->date_filter){
            $q->where('date',$request->date_filter);
    }else{
            $q->where('date',\Carbon\Carbon::now()->toDateString());
    }
})->get();

我需要查询语法或 Laravel Eloquent 语法。

谁能帮我?感谢您的关注 :)

标签: phpmysqlsqllaraveleloquent

解决方案


我可以为您提供正常的查询语法LEFT JOIN

您的查询的问题是您正在通过在子句INNER JOIN中的左连接表上应用条件来执行此操作。WHERE您可以按如下方式获得所需的结果:

select * from
(select b.*, bo.*,  -- use the needed column names with proper alias here. I have used *
        row_number() over (partition by b.id order by bo.date desc) as rn
  from branches b 
  left join branch_operationals bo on b.id = bo.branch_id and date <= 2020-12-21) t 
where rn = 1

推荐阅读