2

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.

Pasindu Jayanath
  • 892
  • 10
  • 27
  • Just had a quick read of this, and although I'm not an SQL expert, joining tables using 'not equals' (!=) seems weird. I would use 'equal' (=) and put the condition `category_level_2.cat_lvl1_id != category_level_1.id` in a `where` clause. – KolaB May 13 '18 at 18:00
  • Yes, I have tried that also.. But, output not as expected. – Pasindu Jayanath May 13 '18 at 18:06

3 Answers3

4

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
        )
)
Pradeep
  • 9,667
  • 13
  • 27
  • 34
2

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();
KolaB
  • 501
  • 3
  • 11
0
$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();