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,FALSE在where()告诉笨不要逃避查询,这可能搞砸了.
更新:您还可以查看我编写的子查询库.
$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)
小智 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)
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()不是文档化的方法,在将来的版本中可能会出现功能(或存在)的变化.
| 归档时间: |
|
| 查看次数: |
89633 次 |
| 最近记录: |