str*_*oir 28 mysql sql union activerecord codeigniter
如何使用PHP CodeIgniter框架的活动记录查询格式进行UNION查询?
Zac*_*ack 34
CodeIgniter的ActiveRecord不支持UNION,因此您只需编写查询并使用ActiveRecord的查询方法.
$this->db->query('SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2');
Run Code Online (Sandbox Code Playgroud)
小智 23
这是我曾经使用的一种快速而肮脏的方法
// 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);
Run Code Online (Sandbox Code Playgroud)
不是我最好的工作,但它解决了我的问题.
注意:我不需要订购结果.
Som*_*luk 21
通过使用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();
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法在模型中获取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();
Run Code Online (Sandbox Code Playgroud)
这样,SQL语句将在$ subquery变量中,而不实际执行它.
很久以前你问过这个问题,所以也许你已经得到了答案.如果没有,这个过程可能会成功.