【问题标题】:How to left join then get the latest row in second table using where date [closed]如何左连接然后使用 where 日期获取第二个表中的最新行 [关闭]
【发布时间】:2021-03-30 22:01:59
【问题描述】:

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

Images on imgur

我认为这是从表 branches 到表 branch_operationals 的左连接,我应该将 where date 放入查询中。

以下是示例:

表格branches

id code name
1 T2QD5 NewYork_Spot
2 MKGHB London_Spot
3 IGHCZ Miami_Spot
4 PJDSO Tokyo_Spot

表格branch_operationals

id branch_id date status
1 2 2020-12-05 closed
2 2 2020-12-06 closed
3 3 2020-12-06 open
4 2 2020-12-06 closed
5 2 2020-12-06 open
6 1 2020-12-16 closed

预期结果

id (from 'branches.id') code name date status
1 T2QD5 NewYork_Spot 2020-12-09 closed
2 MKGHB London_Spot 2020-12-09 open
3 IGHCZ Miami_Spot 2020-12-09 open
4 PJDSO Tokyo_Spot 2020-12-09 null

这是我当前的查询:

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

但是,它返回 null(空数据)。但是当我删除where 语句时,它会显示表branch_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 语法。

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

【问题讨论】:

标签: php mysql sql laravel eloquent


【解决方案1】:

也许对你有用

select b.id ,b.code,b.name ,'2020-12-06' date ,o.status from branch b 
left join  ( select  bo.id, bo.branch_id, bo.date, bo.status from
  (select branch_id , max(id) id  from branch_operationals where date='2020-12-06' group by branch_id ) as tmp
  join branch_operationals bo on bo.id=tmp.id ) as o on b.id=o.branch_id

【讨论】:

【解决方案2】:

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

您的查询的问题是您正在通过在WHERE 子句中的左联接表上应用条件来执行INNER JOIN。您可以通过以下方式达到预期的效果:

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

【讨论】:

  • 我已经试过你的查询,把它的返回 = 'branches' 中的所有数据 + 'branch_operationals' 中的空数据,先生
  • 好的,表示branch_operationals表中没有给定日期的数据。
  • 不,我需要的是从 branch_operationals 获取每个“分支”的最后一个结果
  • 完成!!现在检查答案!
  • 返回 #1060 - 列名“id”重复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2021-04-06
  • 2015-08-11
  • 1970-01-01
  • 2020-06-09
  • 2021-12-15
  • 1970-01-01
相关资源
最近更新 更多