如何以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
Run Code Online (Sandbox Code Playgroud)
我用以下方法执行它.
这是唯一正确的方法还是你有任何改进建议?
$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 ");
Run Code Online (Sandbox Code Playgroud)
cla*_*219 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();
}
Run Code Online (Sandbox Code Playgroud)