Rock笔记
~/rocknotes/articles/346.md article
// article · laravel

Laravel UNION 联合查询

需求:现有两个表,需要对这两个表进行联合查询,对两个表都符合结果的数据行进行并集,例如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 replies

最新回复 ↓
// 暂无回复

回复功能沿用原详情页:前往原页面参与讨论 →