codeigniter活动logging中的子查询

SELECT * FROM certs WHERE id NOT IN (SELECT id_cer FROM revokace); 

如何在CodeIgniter活动logging中编写上述select语句?

->where()支持将任何string传递给它,并将在查询中使用它。

你可以尝试使用这个:

 $this->db->select('*')->from('certs'); $this->db->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE); 

where()中的,NULL,FALSE告诉CodeIgniter不要转义查询,这可能会搞砸了。

更新 :你也可以看看我写的子查询库 。

 $this->db->select('*')->from('certs'); $sub = $this->subquery->start_subquery('where_in'); $sub->select('id_cer')->from('revokace'); $this->subquery->end_subquery('id', FALSE); 

不build议使用_compile_select()_reset_select()函数。
而是使用get_compiled_select()

 #Create where clause $this->db->select('id_cer'); $this->db->from('revokace'); $where_clause = $this->db->get_compiled_select(); #Create main query $this->db->select('*'); $this->db->from('certs'); $this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE); 

CodeIgniter活动logging目前不支持子查询,但我使用以下方法:

 #Create where clause $this->db->select('id_cer'); $this->db->from('revokace'); $where_clause = $this->db->_compile_select(); $this->db->_reset_select(); #Create main query $this->db->select('*'); $this->db->from('certs'); $this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE); 

_compile_select()和_reset_select()是两个未公开的(AFAIK)方法,它们编译查询并返回sql(不运行它)并重置查询。

在主要的查询中,where子句中的FALSE告诉codeigniter不要转义查询(或者添加反引号等),这会搞乱查询。 (NULL是因为where子句有一个可选的第二个参数,我们没有使用)

然而,你应该知道,_compile_select()和_reset_select()没有logging的方法,有可能在未来的版本中function(或存在)可能会改变。

对于查询: SELECT * FROM (SELECT id, product FROM product) as product您可以使用的SELECT * FROM (SELECT id, product FROM product) as product

 $sub_query_from = '(SELECT id, product FROM product ) as product'; $this->db->select(); $this->db->from($sub_query_from); $query = $this->db->get() 

请注意,在sub_query_fromstring中,您必须使用... product ) as...之间的空格... product ) as...

原来的问题可能有点晚,但对于未来的疑问可能有帮助。 最好的方法是将内部查询的结果像这样获取到一个数组中

 $this->db->select('id'); $result = $this->db->get('your_table'); return $result->result_array(); 

然后在下面的活动logging子句中使用比数组

 $this->db->where_not_in('id_of_another_table', 'previously_returned_array'); 

希望这可以帮助

 $this->db->where('`id` IN (SELECT `someId` FROM `anotherTable` WHERE `someCondition`='condition')', NULL, FALSE); 

资料来源: http : //www.247techblog.com/use-write-sub-queries-codeigniter-active-records-condition-full-explaination/

我认为这个代码将起作用。 我不知道这是否是在CI中可接受的查询风格,但它在我以前的问题完美的作品。 🙂

 $subquery = 'SELECT id_cer FROM revokace'; $this->db->select('*'); $this->db->where_not_in(id, $subquery); $this->db->from('certs'); $query = $this->db->get(); 
  $where.= '('; $where.= 'admin_trek.trek='."%$search%".' AND '; $where.= 'admin_trek.state_id='."$search".' OR '; $where.= 'admin_trek.difficulty='."$search".' OR '; $where.= 'admin_trek.month='."$search".' AND '; $where.= 'admin_trek.status = 1)'; $this->db->select('*'); $this->db->from('admin_trek'); $this->db->join('admin_difficulty',admin_difficulty.difficulty_id = admin_trek.difficulty'); $this->db->where($where); $query = $this->db->get();