복붙노트

[SQL] CodeIgniter의 액티브 레코드 패턴 UNION 쿼리

SQL

CodeIgniter의 액티브 레코드 패턴 UNION 쿼리

어떻게 PHP CodeIgniter는 프레임 워크의 액티브 레코드 쿼리 형식 UNION 쿼리를 할까?

해결법

  1. ==============================

    1.당신이 당신의 쿼리를 작성하고 액티브의 쿼리 방법을 사용하므로 CodeIgniter의의 액티브는 UNION을 지원하지 않습니다.

    당신이 당신의 쿼리를 작성하고 액티브의 쿼리 방법을 사용하므로 CodeIgniter의의 액티브는 UNION을 지원하지 않습니다.

    $this->db->query('SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2');
    
  2. ==============================

    2.이것은 내가 한 번 사용하는 신속하고 더러운 방법

    이것은 내가 한 번 사용하는 신속하고 더러운 방법

    // Query #1
    
    $this->db->select('title, content, date');
    $this->db->from('mytable1');
    $query1 = $this->db->get()->result();
    
    // Query #2
    
    $this->db->select('title, content, date');
    $this->db->from('mytable2');
    $query2 = $this->db->get()->result();
    
    // Merge both query results
    
    $query = array_merge($query1, $query2);
    

    아니 내 최고의 작품,하지만 내 문제를 해결했다.

    참고 : 나는 결과를 주문할 필요가 없었다.

  3. ==============================

    3.last_query ()를 사용하여 노동 조합을 수행함으로써, 애플리케이션의 성능을 방해 할 수있다. 때문에 하나의 조합을 위해 3 개 쿼리를 실행하는 데 필요합니다. 즉 "N"조합 "N + 1"쿼리. 그것은 훨씬 1-2 쿼리 조합에 대한 영향을주지 않습니다. 많은 쿼리 또는 테이블의 조합이 큰 데이터를 갖는 경우 그것은 문제를 줄 것이다.

    last_query ()를 사용하여 노동 조합을 수행함으로써, 애플리케이션의 성능을 방해 할 수있다. 때문에 하나의 조합을 위해 3 개 쿼리를 실행하는 데 필요합니다. 즉 "N"조합 "N + 1"쿼리. 그것은 훨씬 1-2 쿼리 조합에 대한 영향을주지 않습니다. 많은 쿼리 또는 테이블의 조합이 큰 데이터를 갖는 경우 그것은 문제를 줄 것이다.

    이 링크는 당신에게 많은 도움이 될 것입니다 : 활성 기록 서브 쿼리

    우리는 수동 쿼리 활동 기록을 결합 할 수 있습니다. 예:

    // #1 SubQueries no.1 -------------------------------------------
    
    $this->db->select('title, content, date');
    $this->db->from('mytable');
    $query = $this->db->get();
    $subQuery1 = $this->db->_compile_select();
    
    $this->db->_reset_select();
    
    // #2 SubQueries no.2 -------------------------------------------
    
    $this->db->select('title, content, date');
    $this->db->from('mytable2');
    $query = $this->db->get();
    $subQuery2 = $this->db->_compile_select();
    
    $this->db->_reset_select();
    
    // #3 Union with Simple Manual Queries --------------------------
    
    $this->db->query("select * from ($subQuery1 UNION $subQuery2) as unionTable");
    
    // #3 (alternative) Union with another Active Record ------------
    
    $this->db->from("($subQuery1 UNION $subQuery2)");
    $this->db->get();
    
  4. ==============================

    4.당신은 모델에서 SQL 문을 얻기 위해 다음과 같은 방법을 사용할 수 있습니다 :

    당신은 모델에서 SQL 문을 얻기 위해 다음과 같은 방법을 사용할 수 있습니다 :

    $this->db->select('DISTINCT(user_id)');
    $this->db->from('users_master');
    $this->db->where('role_id', '1');
    
    $subquery = $this->db->_compile_select();
    $this->db->_reset_select();
    

    이 방법은 SQL 문은 실제로 그것을 실행하지 않고 $ 부질 변수에있을 것입니다.

    당신은 이미 답을 가지고있다 그래서 아마 오래 전에이 질문을했다. 하지 않을 경우,이 프로세스는 트릭을 할 수 있습니다.

  5. ==============================

    5.다음과 같이 somnath huluks 답을 수정하여, 내가 DB_Active_rec 클래스에이 다음과 같은 변수 및 함수를 추가 :

    다음과 같이 somnath huluks 답을 수정하여, 내가 DB_Active_rec 클래스에이 다음과 같은 변수 및 함수를 추가 :

    class DB_Active_records extends CI_DB_Driver
    {
    
       ....
    
       var $unions;
    
       ....
    
        public function union_push($table = '')
        {
            if ($table != '')
            {
                $this->_track_aliases($table);
                $this->from($table);
            }
    
            $sql = $this->_compile_select();
    
            array_push($this->unions, $sql);
            $this->_reset_select();
        }
    
        public function union_flush()
        {
            $this->unions = array();
        }
    
        public function union()
        {
            $sql = '('.implode(') union (', $this->unions).')';
            $result = $this->query($sql);
            $this->union_flush();
            return $result;
        }
    
        public function union_all()
        {
            $sql = '('.implode(') union all (', $this->unions).')';
            $result = $this->query($sql);
            $this->union_flush();
            return $result;
        }
    }
    

    그러므로 사실상 db_driver에 의존하지 않고 노동 조합을 사용할 수 있습니다.

    이 방법을 사용 노조, 당신은 단순히 일반 액티브 레코드 쿼리를 만들지 만, GET 대신 union_push 호출.

    참고 : 당신은 당신의 쿼리를 일반 노동 조합 등의 일치 열이 있는지 확인해야

    예:

        $this->db->select('l.tpid, l.lesson, l.lesson_type, l.content, l.file');
        $this->db->where(array('l.requirement' => 0));
        $this->db->union_push('lessons l');
        $this->db->select('l.tpid, l.lesson, l.lesson_type, l.content, l.file');
        $this->db->from('lessons l');
        $this->db->join('scores s', 'l.requirement = s.lid');
        $this->db->union_push();
        $query = $this->db->union_all();
        return $query->result_array();
    

    생산 것입니다 :

    (SELECT `l`.`tpid`, `l`.`lesson`, `l`.`lesson_type`, `l`.`content`, `l`.`file`
    FROM `lessons` l
    WHERE `l`.`requirement`=0)
    union all 
    (SELECT `l`.`tpid`, `l`.`lesson`, `l`.`lesson_type`, `l`.`content`, `l`.`file`
    FROM `lessons` l
    JOIN `scores` s ON `l`.`requirement`=`s`.`lid`)
    
  6. ==============================

    6.나는 액티브 스타일에 UNION을 추가하는 나를 위해 잘 작동이 라이브러리를 발견 :

    나는 액티브 스타일에 UNION을 추가하는 나를 위해 잘 작동이 라이브러리를 발견 :

    https://github.com/NTICompass/CodeIgniter-Subqueries

    하지만 내가 여기 처음 사용 CodeIgniter의의 dev에 지점에서 get_compiled_select () 메소드를 (잡아했다 : https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_query_builder.php - DB_query_builder를 교체한다 DB_active_rec). 아마이 방법은 CodeIgniter의 향후 생산 릴리스에서 사용할 수 있습니다.

    I 시스템 / 데이터베이스에 DB_active_rec.php에 그 방법을 추가하면 그것이 마치 마법처럼 일했다. (나는이 프로덕션 응용 프로그램입니다 같은 CodeIgniter의의 DEV 버전을 사용하지 않았다.)

  7. ==============================

    7.이것은 내가 사용하고있는 솔루션입니다 :

    이것은 내가 사용하고있는 솔루션입니다 :

    $union_queries = array();
    $tables = array('table1','table2'); //As much as you need
    foreach($tables as $table){
        $this->db->select(" {$table}.row1, 
                            {$table}.row2,
                            {$table}.row3");
        $this->db->from($table);
        //I have additional join too (removed from this example)
        $this->db->where('row4',1);
        $union_queries[] = $this->db->get_compiled_select();
    }
    $union_query = join(' UNION ALL ',$union_queries); // I use UNION ALL
    $union_query .= " ORDER BY row1 DESC LIMIT 0,10";
    $query = $this->db->query($union_query);
    
  8. ==============================

    8.이거 한번 해봐

    이거 한번 해봐

    function get_merged_result($ids){                   
        $this->db->select("column");
        $this->db->distinct();
        $this->db->from("table_name");
        $this->db->where_in("id",$model_ids);
        $this->db->get(); 
        $query1 = $this->db->last_query();
    
        $this->db->select("column2 as column");
        $this->db->distinct();
        $this->db->from("table_name");
        $this->db->where_in("id",$model_ids);
    
        $this->db->get(); 
        $query2 =  $this->db->last_query();
        $query = $this->db->query($query1." UNION ".$query2);
    
        return $query->result();
    }
    
  9. ==============================

    9.이 제 1 서브 쿼리를 실행하기 때문에 bwisn의 대답은 모든 것보다 더 작동하지만 성능이 좋지 않다. get_compiled_select 쿼리를 실행하지 않습니다; 나중에 실행이 매우 빠른 것이 그냥 컴파일 이거 한번 해봐

    이 제 1 서브 쿼리를 실행하기 때문에 bwisn의 대답은 모든 것보다 더 작동하지만 성능이 좋지 않다. get_compiled_select 쿼리를 실행하지 않습니다; 나중에 실행이 매우 빠른 것이 그냥 컴파일 이거 한번 해봐

    $this->db->select('title, content, date');
    $this->db->where('condition',value);
    $query1= get_compiled_select("table1",FALSE);
    $this->db->reset_query();
    
    $this->db->select('title, content, date');
    $this->db->where('condition',value);
    $query2= get_compiled_select("table2",FALSE);
    $this->db->reset_query();
    
    $query = $this->db->query("$query1 UNION $query2");
    
  10. ==============================

    10.여기에 내가 만든 솔루션이다 :

    여기에 내가 만든 솔루션이다 :

    $query1 = $this->db->get('Example_Table1');
    $join1 = $this->db->last_query();
    $query2 = $this->db->get('Example_Table2');
    $join2 = $this->db->last_query();
    $union_query = $this->db->query($join1.' UNION '.$join2.' ORDER BY column1,column2);
    
  11. from https://stackoverflow.com/questions/2040655/union-query-with-codeigniters-active-record-pattern by cc-by-sa and MIT license