codeigniter活动记录中的子查询

mar*_*don 63 codeigniter

SELECT * FROM certs WHERE id NOT IN (SELECT id_cer FROM revokace);
Run Code Online (Sandbox Code Playgroud)

如何在CodeIgniter活动记录中编写上面的select语句?

Roc*_*mat 82

->where() 支持将任何字符串传递给它,它将在查询中使用它.

你可以试试这个:

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

,NULL,FALSEwhere()告诉笨不要逃避查询,这可能搞砸了.

更新:您还可以查看我编写的子查询库.

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

  • @iMohammad:CI中的子查询将永远不会被正式支持.并非所有数据库都支持它; CI适用于任何数据库. (13认同)

小智 38

功能_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);
Run Code Online (Sandbox Code Playgroud)

  • 我个人几乎更喜欢这个,因为我能够分割每个子查询并让它们安全地转义并在遵守后做好准备。 (2认同)

mat*_*otu 15

CodeIgniter Active Records当前不支持子查询,但我使用以下方法:

#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);
Run Code Online (Sandbox Code Playgroud)

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

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

但是,您应该知道_compile_select()和_reset_select()不是文档化的方法,在将来的版本中可能会出现功能(或存在)的变化.

  • $这个 - >数据库 - > _ compile_select(); 已弃用,我相信_reset_select()也已弃用.这个答案是绝对的. (5认同)