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

1k Views Asked by At

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.

3

There are 3 best solutions below

1
KolaB On BEST ANSWER

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();
1
sumit saini On
$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();
2
Pradeep On

Hope this will help you :

$sql = "SELECT id, category 
        FROM category_level_1
        WHERE id NOT IN (SELECT DISTINCT cat_lvl1_id FROM category_level_2)";
$query = $this->db->query($sql);
print_r($query->result());

Output :

Array
(
    [0] => stdClass Object
        (
            [id] => 93
            [category] => dummy
        )
)