php - 如何左连接然后使用 where date 获取第二个表中的最新行
问题描述
有谁知道如何查询这个示例表?
我认为这是从表branches
到branch_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 语法。
谁能帮我?感谢您的关注 :)
解决方案
我可以为您提供正常的查询语法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
推荐阅读
- python - 如何使用 Python 操作音符?
- javascript - Chart Js 不更新第一次加载中的值
- android - 在没有 Dagger2 循环依赖的情况下,如何在 AuthenticationInterceptor 的身份验证方法中触发同步刷新令牌调用?
- html - 如何将图像向左对齐,标题和 p 向右对齐
- xml - 在powershell中比较同一父节点的两个xml元素
- python - 您如何在蓝图中引用 Flask 应用程序工厂的其他模块?
- c# - “Freezer.Utils.ZipDeployer”的类型初始化程序引发异常
- rest-assured - RestAssured 使用 foreach 循环解析 Json 数组响应
- c++ - 使用#include 的问题
和 MSVC 2017 - html - Border-Radius 没有创建圆角边框