以codeigniter样式编写联合查询

时间:2013-02-20 11:18:20

标签: codeigniter

如何以Codeigniter样式编写以下查询。

SELECT COUNT(`id`) AS reccount
  FROM 
    (SELECT `id` FROM table1 
     WHERE tid= '101' AND `status` =  1
     UNION ALL
    SELECT `id` FROM table2 
     WHERE tid= '101' AND `status` =  1
     UNION ALL
    SELECT `id` FROM table3
     WHERE tid= '101' AND `status` =  1) t

我使用以下方式执行它。

这是唯一正确的方法还是你有任何改进建议?

 $q = $this->db->query(SELECT COUNT(`id`) AS reccount
                        FROM 
                        (SELECT `id` FROM table1 
                         WHERE tid= '101' AND `status` =  1
                         UNION ALL
                         SELECT `id` FROM table2 
                         WHERE tid= '101' AND `status` =  1
                         UNION ALL
                         SELECT `id` FROM table3
                         WHERE tid= '101' AND `status` =  1) t ");

3 个答案:

答案 0 :(得分:16)

自CodeIgniter 3以来,它已经在Active Record中引入了函数get_compiled_select(),该函数提供了查询字符串而没有实际执行查询。

这允许@MDeSilva方法使用更少的资源,调整如下:

function get_merged_result($ids){                   
    $this->db->select("column");
    $this->db->distinct();
    $this->db->from("table_name");
    $this->db->where_in("id",$model_ids);
    $query1 = $this->db->get_compiled_select(); // It resets the query just like a get()

    $this->db->select("column2 as column");
    $this->db->distinct();
    $this->db->from("table_name");
    $this->db->where_in("id",$model_ids);
    $query2 = $this->db->get_compiled_select(); 

    $query = $this->db->query($query1." UNION ".$query2);

    return $query->result();
}

答案 1 :(得分:1)

您可以使用CI生成联合查询。但是,最新版本比以前更加困难。

DB有一个名为_compile_select的方法,在以前版本的CI中它是公共的,但现在它受到保护,因此您不能只从控制器中调用$this->db->_compile_select()。为了做到这一点,可以:

  1. 创建自定义加载器类以扩展核心/数据库类(即加载MY_DB_active_record而不是CI_DB_active_record)。
  2. 使用一种方法创建自定义activerecord类:

    public function compile_select() {
        return $this->_compile_select();
    }
    
  3. 在您的控制器中,使用我们的公共方法compile_select()

  4. 创建所有必要的查询,将它们编译成字符串数组
  5. 将数组加入单个查询:'(' . implode(') UNION (', $queries) . ')'。您也可以将其包装到自定义AR类中的单独方法中。

答案 2 :(得分:-1)

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();
}
相关问题