如何使用PHP CodeIgniter框架的活动记录查询格式进行联合查询?
发布于 2010-01-12 04:39:29
CodeIgniter的ActiveRecord不支持UNION,因此您只需编写查询并使用ActiveRecord的query方法即可。
$this->db->query('SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2');发布于 2011-12-12 19:39:51
通过使用last_query()进行联合,可能会影响应用程序的性能。因为对于单个联合,它将需要执行3个查询。即用于"n“个联合"n+1”查询。这对1-2查询联合不会有太大影响。但是,如果多个查询或具有大数据的表的联合将会产生问题。
此链接将对您有很大帮助:active record subqueries
我们可以将活动记录与手动查询结合起来。示例:
// #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();发布于 2012-12-17 10:16:16
这是我曾经用过的一种又快又脏的方法。
// 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);不是我最好的作品,但它解决了我的问题。
注意:我不需要对结果进行排序。
https://stackoverflow.com/questions/2040655
复制相似问题