【问题标题】:Laravel query builder - Union All with Skip and TakeLaravel 查询构建器 - 使用 Skip 和 Take 联合所有
【发布时间】:2014-08-06 01:18:56
【问题描述】:

我需要使用此查询从表中获取数据:

(select columns 
   from tableX 
   join tableZ 
   on tableX.id1 = tableZ.other_id)
union all 
(select columns 
   from tableX 
   join tableZ 
   on tableX.id2 = tableZ.other_id) 
LIMIT num1, num2

没有LIMIT,我的查询构建器会得到正确的结果,如下所示(让$first 成为select 的第一个查询,$second 是另一个select 查询):

$first->unionAll($second)->get();

当我尝试输入skip 和/或take 时,结果与上面的第一个查询不同。

$first->unionAll($second)->take(num1)->skip(num2)->get();

来自上述构建器的结果查询(我从DB::getQueryLog() 得到)类似于:

(select columns 
   from tableX 
   join tableZ 
   on tableX.id1 = tableZ.other_id LIMIT num1, num2)
union all 
(select columns 
   from tableX 
   join tableZ 
   on tableX.id2 = tableZ.other_id)

这当然会产生不正确的结果。有谁知道进行第一个查询的解决方法是什么?谢谢!

【问题讨论】:

    标签: php laravel-4 eloquent query-builder


    【解决方案1】:

    您需要将$firstQuery 包装在另一个查询中,如下所示:

    $first->unionAll($second);
    
    $rows = DB::table( DB::raw("({$first->toSql()}) as t") )
    ->mergeBindings($first->getQuery())
    ->take(num1)->skip(num2)
    ->get();
    

    这将导致以下查询:

    select * from (FIRST_QUERY union all SECOND_QUERY) as t limit num1, num2
    

    【讨论】:

    • 对此感到抱歉。我的问题很久以前就得到了回答,忘记接受 narendra 的回答,但你得到了额外答案的投票。
    【解决方案2】:

    一种解决方法是在下面的示例块中使用 DB::select 和 DB::raw 使用原始查询...

        $num1 = 100; // skip first 100 rows
        $num2 = 2;   // take only 2 rows 
    
        $qry_result = DB::select(DB::raw("select * from 
              (
                (select columns from tableX join tableZ on tableX.id1 = tableZ.other_id)
                 union all 
                (select columns from tableX join tableZ on tableX.id2 = tableZ.other_id) 
              ) Qry LIMIT :vskip , :vlimit ") , array('vskip'=>$num1,'vlimit'=>$num2) 
       );                                              
    

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 2020-12-31
      • 2014-02-11
      • 2016-03-30
      • 2018-02-03
      • 2017-06-29
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多