Using Mysql WHERE IN clause in codeigniter

前端 未结 4 1244
Happy的楠姐
Happy的楠姐 2020-11-29 10:24

I have the following mysql query. Could you please tell me how to write the same query in Codeigniter\'s way ?

SELECT * FROM myTable 
         WHERE trans_id         


        
相关标签:
4条回答
  • 2020-11-29 10:39

    try this:

    return $this->db->query("
         SELECT * FROM myTable 
         WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B') 
         AND code!='B'
         ")->result_array();
    

    Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html see Standard Query With Multiple Results (Array Version) section

    0 讨论(0)
  • 2020-11-29 10:44

    You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
    Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

    public function _compile_select($select_override = FALSE)
    public function _reset_select()
    

    Now subquery writing in available And now here is your query with active record

    $this->db->select('trans_id');
    $this->db->from('myTable');
    $this->db->where('code','B');
    $subQuery = $this->db->_compile_select();
    
    $this->db->_reset_select();
    // And now your main query
    $this->db->select("*");
    $this->db->where_in("$subQuery");
    $this->db->where('code !=', 'B');
    $this->db->get('myTable');
    

    And the thing is done. Cheers!!!
    Note : While using sub queries you must use

    $this->db->from('myTable')
    

    instead of

    $this->db->get('myTable')
    

    which runs the query.
    Watch this too

    How can I rewrite this SQL into CodeIgniter's Active Records?

    Note : In Codeigntier 3 these functions are already public so you do not need to hack them.

    0 讨论(0)
  • 2020-11-29 10:53
    $data = $this->db->get_where('columnname',array('code' => 'B'));
    $this->db->where_in('columnname',$data);
    $this->db->where('code !=','B');
    $query =  $this->db->get();
    return $query->result_array();
    
    0 讨论(0)
  • 2020-11-29 10:57

    Try this one:

    $this->db->select("*");
    $this->db->where_in("(SELECT trans_id FROM myTable WHERE code = 'B')");
    $this->db->where('code !=', 'B');
    $this->db->get('myTable');
    

    Note: $this->db->select("*"); is optional when you are selecting all columns from table

    0 讨论(0)
提交回复
热议问题