美文网首页
Laravel UNION联合查询并分页

Laravel UNION联合查询并分页

作者: _不想翻身的咸鱼 | 来源:发表于2022-02-23 18:46 被阅读0次

    UNION联合查询并分页

    $xk =  DB::table('xiaokes')->select(['id','xk_name as name','xk_teacher_id as tid','ke_type','created_at']) 
               ->where('xk_teacher_id',$id); 
     
    $query =  DB::table('zhuanlans')->select(['id','zl_name as name','zl_teacher_id as tid','ke_type','created_at']) 
               ->where('zl_teacher_id',$id)->union($xk); 
     
    $querySql = $query->toSql(); 
    $result = DB::table(DB::raw("($querySql) as a"))->mergeBindings($query) 
               ->orderBy('created_at','desc')->paginate(10); 
    
    

    联合查询用于将两个或更多查询的结果集组合为单个结果集,该结果集包含联合查询中所有查询的全部行。UNION的结果集列名与UNION运算符中第一个Select语句的结果集的列名相同,另一个Select语句的结果集列名将被忽略,且其他查询字段数必须和第一个相同。

    实例:解决两表聚合分页问题

    public function getAllSchool($params, $size = 10)
        {
            $xk =  DB::connection('neworiental_v3')->table('entity_private_school')->select([DB::raw('"4" as type'),'id','name']);
    
            $query =  DB::connection('neworiental_v3')->table('entity_public_school')->select([DB::raw('"2" as type'),'id','name']);
             
            if (isset($params['id']) && $params['id']) {
                $xk = $xk->where('id', '=', $params['id']);
                $query = $query->where('id', '=', $params['id']);
            }
    
            if (isset($params['name']) && $params['name']) {
                $xk = $xk->where('name', 'like', '%'.$params['name'].'%');
                $query = $query->where('name', 'like', '%'.$params['name'].'%');
            }
    
            if (isset($params['status']) && $params['status']) {
                $xk = $xk->where('status', '=', $params['status']);
                $query = $query->where('status', '=', $params['status']);
            }
        
            $query =  $query->union($xk);
            $querySql = $query->toSql();
    
            $result = DB::connection('neworiental_v3')->table(DB::raw("($querySql) as a"))->mergeBindings($query)->orderBy('id', 'ASC')->paginate($size)->toArray();
            return $result;
        }
    

    相关文章

      网友评论

          本文标题:Laravel UNION联合查询并分页

          本文链接:https://www.haomeiwen.com/subject/hutalrtx.html