Laravel UNION 联合查询

Laravel tytrock ⋅ 于 2022-03-24 17:26:18 ⋅ 2472 阅读

需求:现有两个表,需要对这两个表进行联合查询,对两个表都符合结果的数据行进行并集,例如A表有3条符合查询的结果,B表有2条,那么查询的结果就是5条


可以使用union进行联合查询

$billSql =  Table1::select(DB::raw('num,amount,ought_date as action_date,NULL as bill_id'))->where('customer_id',$request->customer_id)->where('ought_date','>=',$request->start_date)->where('ought_date','<=',$request->end_date);
$query =  Table2::select(DB::raw('num,amount,action_date,bill_id'])->where('customer_id',$request->customer_id)->where('action_date','>=',$request->start_date)->where('action_date','<=',$request->end_date)->union($billSql);
$querySql = $query->toSql();
$lists = DB::table(DB::raw("($querySql) as a"))->mergeBindings($query->getQuery())->orderBy('action_date','ASC')->get();


代码中的“NULL as bill_id

因为union联合查询必须有相同数量的列,而有些情况可能其中一个表 会存在另一个表没有并且需要使用的字段,或者需要在其中一个表中添加一个另一个表没有的字段来区分这条数据是从哪个表获取的,那可以将空列(null as columnName)添加到列数更少的查询中,以达到需求。


参考资料:

http://cn.voidcc.com/question/p-sfcpxwiy-px.html

本帖已被设为精华帖!
回复数量: 0
    暂无评论~~
    • 请注意单词拼写,以及中英文排版,参考此页
    • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`, 更多语法请见这里 Markdown 语法
    • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
    • 上传图片, 支持拖拽和剪切板黏贴上传, 格式限制 - jpg, png, gif
    • 发布框支持本地存储功能,会在内容变更时保存,「提交」按钮点击时清空
    Ctrl+Enter