phpmysqlcodeigniterjoinwhere-clause

How to write a SELECT query with a JOIN and a WHERE clause in CodeIgniter


I have two tables, and I want to get all the rows from table1 that meet the where clause conditions, and then join them with table2 based on the join conditions.

Here are the sample tables:

table1:

col1   col2  col3
1      a     val1
2      b     val2
3      c     val3

table2:

col1   col3
1      someval1
2      someval2
3      someval3

Now I want to grab all the rows in table1 where col1 = 2, and join those rows with rows from table2 where table2.col1 = table1.col1. Does that make sense?


Solution

  • It's been a while since I wrote CI, but as per this docs page, your solution might look like this:

    $this->db->select('*');
    $this->db->from('table1');
    $this->db->join('table2', 'table1.col1 = table2.col1');
    $this->db->where('table1.col1', 2);
    
    $query = $this->db->get();
    

    note this answer is in no way to be construed as an endorsement of working with Code Igniter ;-)