2011-04-09 73 views
4

我試圖用Kohana's query builder來建立一個UNION查詢。一切正常,直到我添加一個GROUP BY或ORDER BY子句。如何在Kohana的查詢構建器中使用ORDER BY和GROUP BY構建UNION查詢?

這裏是我正在使用的代碼(簡化):

$query1 = DB::select('p.name') 
    ->from(array('person', 'p')) 
    ->where('p.organization', 'LIKE', 'foo%') 
    ->limit(10); 

$names = DB::select('sh.name') 
    ->union($query1, FALSE) 
    ->from(array('stakeholder', 'sh')) 
    ->where('sh.organization', 'LIKE', 'foo%') 
    ->group_by('name') 
    ->order_by('name') 
    ->limit(10) 
    ->execute() 
    ->as_array(); 

而是在整個查詢的末尾添加GROUP BY和ORDER BY的,它會立即在第二個查詢後添加。

這是本生成SQL:

SELECT sh.name FROM stakeholder AS sh WHERE sh.organization LIKE 'foo%' 
GROUP BY name ORDER BY name LIMIT 10 
UNION 
SELECT p.name from person AS p WHERE p.organization LIKE 'foo%' LIMIT 10; 

我要的是:

SELECT sh.name FROM stakeholder AS sh WHERE sh.organization LIKE 'foo%' 
UNION 
SELECT p.name from person AS p WHERE p.organization LIKE 'foo%' 
GROUP BY name ORDER BY name LIMIT 10; 
+1

你能告訴我們它生成的SQL,和你期望的SQL? – Charles 2011-04-09 03:56:38

回答

6

的條款這裏是從union()方法建立了第一個查詢應用,所以才扭轉哪裏你把他們:

$query1 = DB::select('p.name') 
       ->from(array('person', 'p')) 
       ->where('p.organization', 'LIKE', 'foo%') 
       ->group_by('name') 
       ->order_by('name') 
       ->limit(10); 

$names = DB::select('sh.name') 
       ->union($query1, FALSE) 
       ->from(array('stakeholder', 'sh')) 
       ->where('sh.organization', 'LIKE', 'foo%') 
       ->execute() 
       ->as_array(); 

你也可以刪除多餘的->limit(10)$names,因爲它將被忽略並被$query1中的那個所取代。

0

2011年的答案在Kohana 3.3中不起作用。

但我發現這個模塊:https://github.com/Invision70/kohana-orm-union

+0

這很奇怪。我很確定我已經完成了3.3中的聯合查詢......但可能是錯誤的。 – 2015-08-14 03:28:31

0

你也可以使用ORM的db_pending延長Kohana_ORM:

class ORM extends Kohana_ORM { 
    public function union($table, $all = TRUE) 
    { 
     // Add pending database call which is executed after query type is determined 
     $this->_db_pending[] = array(
      'name' => 'union', 
      'args' => array($table, $all), 
     ); 

     return $this; 
    } 
} 

用法:

ORM::factory('MyModel') 
    ->union(DB::select(DB::expr("'RP' id, 'Pasantías' name, 'Pasantías' short_name, 'R' parent_id, null data"))) 
    ->union(DB::select(DB::expr("'RC' id, 'Capacitación' name, 'Capacitación' short_name, 'R' parent_id, null data"))) 
    ->join(['catalogo', 'p'])->on('catalogo.parent_id', '=', 'p.id') 
    ->where('p.parent_id', 'is', NULL) 
    ->where('catalogo.id', 'not in', ['RV', 'RPA', 'RPT']);