codeigniterinner-joincodeigniter-3query-buildercodeigniter-datamapper

Codeigniter 3 - Query Builder 'join' Method '!=' operator is not giving expected output


Not a Duplicate Question!!!


I am using CodeIgniter 3 - Query Builder Class with MySQLi.


Tables in DB:

'category_level_1' Table:
enter image description here

'category_level_2' Table:
enter image description here


Query in model.php:

$query = $this->db
  ->select('category_level_1.id, category_level_1.category')
  ->from('category_level_1')
  ->join('category_level_2', 'category_level_2.cat_lvl1_id != category_level_1.id', 'inner')
  ->group_by('category_level_1.id')
  ->get();

Output :

enter image description here
Inner-Join not working.


Expected Output :

enter image description here
Only need to output records in 'category_level_1' Table which are not related with 'category_level_2' Table.


Issue:

As showed above, output values are not as expected according to '!=' operator is not working with 'inner' join.


Solution

  • I suggest you try using a left orright join and a where clause. Give the following a go:

    $query = $this->db
      ->select('category_level_1.id, category_level_1.category')
      ->from('category_level_1')
      ->join('category_level_2', 'category_level_2.cat_lvl1_id = category_level_1.id', 'left')
      ->where('category_level_2.cat_lvl1_id IS NULL')
      ->group_by('category_level_1.id')
      ->get();