2011-04-09 3 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를 추가, 그것은이 두 번째 쿼리 후 즉시 추가 것 : 여기

내가 사용하고 코드 (간체)이다.

이이 생성하는 SQL입니다 : 그래서 그냥 어디 역

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

답변

6

조항 여기 union() 방법에서 설정 한 첫 번째 쿼리에서 적용됩니다

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; 

내가 원하는 것은 당신은 그들을두고있어 :

$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

Kohana 3.3에서 2011 년 답변이 작동하지 않습니다. 3.3.

하지만이 모듈을 발견 https://github.com/Invision70/kohana-orm-union

+0

이상 하네. 나는 3.3과 같은 union 질의를했지만 ... 틀릴 수도 있습니다. –

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']); 
관련 문제