phpcodeignitersubqueryquery-builderwhere-in

How to write a subquery inside of CodeIgniter's where_in()


I want to write a subquery inside if a WHERE IN condition with CodeIgniter's query builder.

How can I convert this WHERE clause to a query builder script?

where kd_x in (select kd_x from master_code where a='11921212')

I'm trying to do this with query builder like this, but is doesn't give me any data:

$this->db->where_in('kd_x',array('select kd_x from MT_master where a="11921212"'));

Solution

  • ->where() you can use 2nd and 3rd argument, so that any string you can pass

    $this->db->where('`kd_x`  IN (select `kd_x` from `MT_master` where a="11921212")', NULL, FALSE);
    

    OR

    //Create where clause
    $this->db->select('kd_x')
             ->where('a','11921212')
             ->from('MT_master');
    $where_clause = $this->db->get_compiled_select();
    
    //Create main query
    $this->db->select('*');
         ->from('your_table');
         ->where("`kd_x` IN ($where_clause)", NULL, FALSE);